Not understanding why my program doesnt work - python

I am pretty new to programming and python. My question is I had these lines running but first I'll explain. I wanted to write a program that would ask your weight in pounds and my program would convert it to kgs. Now here is the correct answer:
weight = input ("What is your weight in pounds? ")
converter = int(weight) * 0.45
print (converter)
Now I wanted it to work for decimals (lbs in decimals). So I wrote this:
weight = input ("What is your weight in pounds? ")
converter = int(0.45) * weight
print (converter)
But the second program doesn't work. Can anyone explain why? Thank you

int(0.45) converts the 0.45 to an integer (whole number) which is truncated to 0 so you are effectively multiplying any input by 0.
In the original program you were taking the input as a string with the input command and then converting that string to an integer with int(weight). If you want to have the program work with decimals then you would want to use float(weight)

In your second program you are casting to int the number 0.45 which evaluates to be 0 In order for this to work with float, just remove the int() before the 0.45 , because it's a floating number the whole expression will be float.

weight = input ("What is your weight in pounds? ")
The above code always returns a string.
If you try running the following after the above line you will notice it prints str, which means its a string data type.
print(type(weight))
Now that we know the type of data store in the variable weight is of str, we need to ensure that we convert it into a number before using it in a mathematical equation.
In your case i understand that, in your second program you want to have your output of the variable converter in decimals.
hence you have to rewrite the line as follows:
converter = 0.45 * float(weight)
In order to ensure that the converter variable holds a decimal value, you can try:
print(type(converter))
if the above line gives the output as float, you have got your intended output.
For future reference, you may refer this link which shows all the data types available in Python: https://docs.python.org/3/library/datatypes.html

Related

ValueError when trying to create float from (50, 20.0, 3.1599)

So I am stuck, I know the error is a ValueError unable to convert string to float. I just don't understand why. This is the lab I am working on:
Output each floating-point value with two digits after the decimal
point, which can be achieved as follows:
print('{:.2f}'.format(your_value))
Ex: If the input is:
20.0
3.1599
the output is:
1.58
7.90
63.20
Your program must define and call the following driving_cost()
function. Given input parameters driven_miles, miles_per_gallon, and
dollars_per_gallon, the function returns the dollar cost to drive
those miles. Ex: If the function is called with: 50 20.0 3.1599 the function returns: 7.89975 def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon)
Your program should call the function three times to determine the gas
cost for 10 miles, 50 miles, and 400 miles.
Here is my code:
def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon):
cost = (driven_miles/miles_per_gallon)*dollars_per_gallon
return cost
if __name__ == '__main__':
driven_miles = int(input())
miles_per_gallon = float(input())
dollars_per_gallon = float(input())
for i in range(len(driven_miles)):
cost = driving_cost(driven_miles[i], miles_per_gallon, dollars_per_gallon)
print('{:.2f}'.format(cost))
As I stated above, I am extremely new to this, just trying to understand why I am getting a ValueError: could not convert string to float: when entering the input like this (50, 20.0, 3.1599). But if I enter the other value with the breaks in it like:
20.0
3.1599
it goes through for me. I am definitely missing something.
input() reads one line from standard input. Your code takes that line and tries to convert it to an int or float. But python can't interpret (50, 20.0, 3.1599) as an int or float.
You can write your program to parse (50, 20.0, 3.1599) as an input string. Or you can write your program to read 3 lines of input an parse each as one of those values. Or you could write your program to support both. But you can't write your program to read 3 lines of input and then expect it to successfully parse alternative formats of input data.
If you are trying to input all 3 of those inputs to the program in the format the program currently expects, separate each line with the line terminator. In a Posix flavored shell that could look something like:
python myprogram.py <<<"1
2
3
"
It's a much better technique than individually typing in every input as you test your program!
As an aside, in the real world, input() is very rarely used. In fact interactive program input is very rare in everywhere except computer programming coursework. In the real world user input is more often provided as command line arguments. If standard input is the source of data it's often formatted with a spec like Json or Yaml (etc) that doesn't leave ambiguity in how the data should be formatted.
Even if your coursework requires you to collect ostensibly interactive user input, try to remove it from SO questions whenever possible. Instead hard code the input data into the code you post to make your code more reproducible. input() is a common tripping point so if you can take it out of the equation, do so. I suspect if you would have tried to do that here, you would have quickly realized that no single variable in your program was a proper place to store the input (50, 20.0, 3.1599).
Good luck with your studies!
Since you're trying to use a loop, it sounds like you want to use a List:
def driving_cost(distance, miles_per_gallon, dollars_per_gallon):
print('{:.2f}'.format(distance/miles_per_gallon*dollars_per_gallon))
MPG = float(input('Enter miles per gallon (eg 20.0): '))
DPG = float(input('Enter dollars per gallon (eg 3.1599): '))
driven_miles_list = [10, 50, 400]
for distance in driven_miles_list:
driving_cost(distance, MPG, DPG)

Wont show result of calculation

i am very new to coding and stumbled upon my first problem I don't know how to solve:
weight_in_pounds=(input('How much pounds do you weigh? '))
weight_in_kilograms=weight_in_pounds*int(0.45)
print('You weigh '+ weight_in_kilograms +' kg.')
This is what I typed in and this is the result if I run it:
How much pounds do you weigh? 213
You weigh kg.
I have no idea why it doesn't show the answer. For this example I typed in 213 but instead of the result it just shows a space. What did I do wrong?
You're converting 0.45 to an integer. 0.45 as an integer is 0. weight_in_pounds*0 = 0.
You're inputting weight_in_pounds, which makes it a string. Python is a bit weird with types, so a string * 0 is just an empty string.
You should first remove the conversion to an integer on the 2nd line and add a conversion to a float (decimal) to the first. I.E: weight_in_pounds=float(input('How much pounds do you weigh? '))
With very minimal changes you can get it to work:
weight_pound = int(input('How much do you weigh in pounds? '))
weight_kg = weight_pound*0.45
print('You weigh {0} kg.'.format(weight_kg))
The problem is as Brian mentioned. It's a matter of types.
Also you can only concatenate strings and so you'll have to use such formatting to get it to display.
* Repetition - Creates new strings, concatenating multiple copies of the same string
Explaination of operations on strings
You are repeating the same string zero times.

How to get a irrational number as a user input in python?

How to get a irrational number as a user input in python? Like squared root of 2
something like :
Irrational_Number = float(input("ENTER a Irrational Number : "))
>>> ENTER a Irrational Number : (USER INPUT)
and then user put a Number like N-th root of K (i mean the number in this format not the exactly this kind of String) " Pi " , " e " or " Phi " in command Line.
How User Can do this Directly in command line python (3.8)
I searched this question everywhere but there is nothing about that...
First of all, you're casting your input to a float, so to be precise (which is important if we're bandying around terms like Irrational Number) then we have to highlight the assumption that were talking about approximations to Irrational Numbers here.
That done, there's a few ways you can explore a solution:
The first would be to define a namespace in which you map string names to numeric equivalents - a simple dict could do the trick, like:
numbers_as_words = { "e",2.718281828459045
"pi",3.141592653589793
"phi",1.618033988749895
"sqr2",1.4142135623730951
"feet_to_meters",0.3048
"lbs_to_kg",0.453592
"miles_to_kilometers",1.60934
"gallons_to_litres",3.78541 }
I've padded that out with some non-irrational place-holders too, in case you wanted to embed some simple conversion type logic.
Then, you'd need to take your input as a string, perform a simple replace function on the string to resolve any matching strings, and viola , you've got a mixed numeric/string input method.
def replace_names_and_return_float(user_input, mapping):
for k,v in mapping.items():
user_input = user_input.replace(k,str(v))
return float(user_input)
Irrational_Number = replace_names_and_return_float(input("ENTER a Irrational Number : "), numbers_as_words )
Then it's just up to you to maintain that numbers_as_words dictionary to contain all the substitutions you want to recognise. That could get tedious, but it ought to be enough to get you started.
If you find some official list of irrational number approximations, you might be able to download it, and construct a numbers_as_words mapping as an automated process, but I've not Googled that just now.
Please find below code snippet:
import re
g = input("Enter your irrational number : ")
if g=='pi':
g=math.pi
elif "root" in g:
root=float(re.search('[0-9]+', g).group())
number=float(re.search('(\d+)(?!.*\d)', g).group())
g=number**(1/float(root))
print(g)
Advantage of using this would be:
There is no manual value inserted
You can build it for every symbol present in math lib
Can be extended for other operations as well

How can test a variable if it is an integer?

As the title might specify, I want to ask how can I test a variable if it is an integer. I have seen other topics and they don't seem to have code that works or that I know how to use.
print("Enter the weight of the bag in grams.")
weight = float(input()) # float was used as it might be a decimal sometimes
amtcoin = weight / 3.56
How do I test if amtcoin is a integer? As the variable suggests, it is the amount of coins and you cannot have a fraction of a coin.
Thanks.
You can convert to float as you did and then check with is_integer method:
float(weight).is_integer()
amtcoin variable is instance of class you declare it. Declare it as float and if you want to know if it's a fraction or not check amtcoin % 1 == 0
Try something like this:
if int(amtcoin) == amtcoin:
do_something()
If it is int, this condition will be met.

how to print decimal values in python

print("enter start() to start the program")
def start():
print("This script converts GBP into any currency based on the exchange rate...")
print(" ") #enters a line
exchangeRate = int(input("Enter the exchange rate (Eg: 0.80)"))
print("how much would you like to convert???")
gpb = int(input())
print(gpb*exchangeRate)
If I put the exchange-rate at 0.81 and I enter £1 it always returns 0.
Use float() instead of int() with your input() call. I.e.,
gpb = float(input())
otherwise if the user enters 0.81, int() will truncate this to 0 during the conversion.
By using float() you'll keep the decimal value supplied as input and your computation should yield the result you expect.
You specified type as int.....those are whole numbers (0,1,2,3,4,5,6,7,8....) when you multiply 1 by 0.81 you get 0.81.....key number for integers is the one before dot,in this case zero.So like previous answer shortly said just change type of variable.

Categories

Resources