This question already has an answer here:
- How can I read inputs as numbers? 17 answers
- How to convert strings into integers in Python? 14 answers
I am quite a newbie in Python. I wrote this and got this error when i typed a letter in the input:
TypeError: unorderable types: str() >= int()
Here is the code that I wrote:
user_input = input('How old are you?: ')
if user_input >= 18:
print('You are an adult')
elif user_input < 18:
print('You are quite young')
elif user_input == str():
print ('That is not a number')
user_input
is astr
, you're comparing it to anint
. Python does not know how to do that. You will need to convert one of them to the other type to get a proper comparison.For example, you can convert a string to an integer with the
int()
function:You should do:
so as you explicitly cast your input as int, it will always try to convert the input into an integer, and will raise a valueError when you enter a string rather than an int. To handle those cases, do:
So, the full solution might be like below: