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.
Related
I'm trying to use an input function in python and want to format how the input actually displays in python.
The code is currently:
price = float(input("Enter value: "))
and prints out the following if I input 9.0 (note that python does this automatically without using a print statement).
Enter value: 9.0
How do I format the output so that it only shows the value with 0 decimal points i.e., should print out
Enter value: 9
Using a print() statement and {:,g} is not an option in this exercise.
You can modify your code as:
price = float(input("Enter value: "))
price = int(price)
print(price)
This will convert float into an integer.
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
I want to check if a user entered a number as percent format (18.06) instead of decimal format (0.1806), and always convert to decimal format.
Currently, I check to see if the value > 1, and if so, divide by 100. This works in my use case, but I can imagine some edge cases where it doesn't work. Is there a better solution?
UPDATE: let's assume it's a float, and therefore all strange characters, i.e. %s, have been removed.
Since you likely take the user input as a string(?) you could check the last digit to see if it is a "%"
if user_input[-1] == "%":
user_val = float(user_input[:-1]) / 100.0
else:
user_val = float(user_input)
assuming that you want to keep the original str value as well, otherwise use the same var.
It would be preferable imho to be explicit with the users as to the format that you want the input to be, as (pointed out by #pushkin) vals can be 0.5% as a valid input.
to be clear about the format of the input, then perhaps
while True: # if Py2.7 use raw_input instead of input
user_res = input("For 5% please enter 5. For 44.7%, please enter 44.7")
try: # handle invalid input that is not a number
user_val = float(user_res)
if (user_val >100) or (user_val < 0): # check upper and lower bound
print("Invalid entry- outside bonds")
else:
confirm = input("{}% to be recorded as your entry- confirm (Y/n) ".format(user_val))
if confirm.upper == "Y":
break
else:
print("Please try again")
except:
print("Invalid entry- nAn")
Someone downed me for this answer even though it's the only one and not marked as duplicate, so if you find it useful please upvote- thanks.
I tried to make a short program that works out the famous Drake equation. I got it to accept integer inputs, decimal inputs, and fractional inputs. However, I get this error when the program attempts to multiply them (right after I input all necessary values the error happens):
Traceback (most recent call last)
File "C:/Users/Family/Desktop/Programming/Python Files/1/DrakeEquation1.py", line 24, in <module>
calc() #cal calc to execute it
File "C:/Users/Family/Desktop/Programming/Python Files/1/DrakeEquation1.py", line 17, in calc
calc = r*fp*ne*fl*fi*fc*l
TypeError: can't multiply sequence by non-int of type 'str'
My code is as follows:
def intro():
print('This program will evaluate the Drake equation with your values')
def calc():
print('What is the average rate of star formation in the galaxy?')
r = input()
print('What fraction the stars have planets?')
fp = input()
ne = int(input('What is the average number of life supporting planets (per star)?'))
print('What fraction of these panets actually develop life')
fl = input()
print('What fraction of them will develop intelligent life')
fi = input()
print('What fraction of these civilizations have developed detectable technology?')
fc = input()
l = int(input('How long will these civilizations release detectable signals?'))
calc = r*fp*ne*fl*fi*fc*l
print('My estimate of the number of detectable civilizations is ' + calc + ' .')
if __name__=="__main__":
intro() #cal intro to execute it
calc() #cal calc to execute it
What do I need to change in order to fix this problem?
You need to convert your input values to floats.
r = float(input())
(Note: in Python versions less than 3, use raw_input instead of input.)
And so on for the other variables. Otherwise you're attempting to multiply a string by a string.
Edit: as others have pointed out, calc additionally cannot be concatenated to the surrounding strings using the + operator. Use string substitution for that:
print('My estimate of the number of detectable civilizations is %s.' % calc)
Contrary to the answers asserting that the problem's with not casting the output of input to the correct type. The real problem is
Not properly validating the input to the program, and
Trying to concatenate a str with a number on this line:
print('My estimate of th..." + calc + ' .')
Your program runs fine for me given integers, floats and fractional values as input. Given '1' and '1' (quoted) as the first two inputs, it returns the error you're seeing.
You have converted some values into appropriate types for arithmetic but not the others. The real values should be passed to float() and the ratios should be parsed and computed (or use the Fraction type, or force your user to input a real). An example of the latter is posted below:
print('What is the average rate of star formation in the galaxy?')
r = float(input())
print('What fraction the stars have planets?')
fp = float(input())
ne = int(input('What is the average number of life supporting planets (per star)?'))
print('What fraction of these panets actually develop life')
fl = float(input())
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
So, I suggest you to use raw_input to avoid potential errors.
I'm making a game where the "Computer" tries to guess a number you think of.
Here's a couple snippets of code:
askNumber1 = str(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 = str(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'
That's the computer asking if it got the number right, using random.randint to generate a random number. The problems are 1) It won't let me combine strings and integers, and 2) Won't let me use the variables as the min and max numbers.
Any suggestions?
It would be better if you created a list with the numbers in the range and sort them randomly, then keep poping until you guess otherwise there is a small possibility that a number might be asked a second time.
However here is what you want to do:
askNumber1 = int(str(raw_input('What range of numbers do you want? Name the minimum number here.')))
askNumber2 = int(str(raw_input('Name the max number you want here.')))
You save it as a number and not as a string.
As you suggested, randint requires integer arguments, not strings. Since raw_input already returns a string, there's no need to convert it using str(); instead, you can convert it to an integer using int(). Note, however, that if the user enters something which is not an integer, like "hello", then this will throw an exception and your program will quit. If this happens, you may want to prompt the user again. Here's a function which calls raw_input repeatedly until the user enters an integer, and then returns that integer:
def int_raw_input(prompt):
while True:
try:
# if the call to int() raises an
# exception, this won't return here
return int(raw_input(prompt))
except ValueError:
# simply ignore the error and retry
# the loop body (i.e. prompt again)
pass
You can then substitute this for your calls to raw_input.
The range numbers were stored as strings. Try this:
askNumber1 =int(raw_input('What range of numbers do you want? Name the minimum number here.'))
askNumber2 =int(raw_input('Name the max number you want here.'))
That's to get the range of numbers they want the computer to use.
print 'Is this your number: ' + str(random.randint(askNumber1, askNumber2)) + '?'