Reputation: 13
I would like to be able to display double the value of any number the user inputs.
spam = int(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))
The problem is if the user inputs a decimal, ie 3.4. It comes up with an error since it becomes a float value.
Traceback (most recent call last):
File "<pyshell#66>", line 1, in <module>
spam = int(input('choose any number: '))
ValueError: invalid literal for int() with base 10: '3.4'
Is there a simple way to let the user input any number (be it integer or float value)?
This is in python 3, so raw_input doesn't work.
Upvotes: 1
Views: 109
Reputation: 31
Do this:
spam = input('choose any number: ')
try:
print('Your number doubled is: ' ,int(spam)*2)
except ValueError:
print('Your number doubled is: ' ,float(spam)*2)
The way this works is that it will try to convert into an integer, and if that doesn't work it will convert it into a float.
Upvotes: 0
Reputation: 36702
You could use float
:
spam = float(input('choose any number: '))
print('Your number doubled is: ' + str(spam*2))
Upvotes: 0