Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compare a string and an integer? [duplicate]

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')
like image 954
Keretto Avatar asked May 11 '26 17:05

Keretto


2 Answers

You should do:

user_input = int(input('How old are you?: '))

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 that can't be converted to an int. To handle those cases, do:

except ValueError:
    print('That is not a number')

So, the full solution might be like below:

try:
    user_input = int(input('How old are you?: '))
except ValueError:
    print('That is not a number')
else:
    if user_input >= 18:
        print('You are an adult')
    else:
        print('You are quite young')
like image 156
Ahsanul Haque Avatar answered May 14 '26 05:05

Ahsanul Haque


user_input is a str, you're comparing it to an int. 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:

user_input = int(input('How old are you?: '))
like image 22
bperson Avatar answered May 14 '26 07:05

bperson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!