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

こ雲淡風輕ζ 提交于 2019-12-29 08:58:17

问题


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')

回答1:


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 rather than 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?: '))

    if user_input >= 18:
         print('You are an adult')
    else:
         print('You are quite young')
except ValueError:
    print ('That is not a number')



回答2:


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?: '))



回答3:


user_input = input('How old are you?: ')
try:
    age = int(user_input)
except ValueError:
    print('Please use an integer for age')
    continue          # assuming you have this is an input loop
if user_input < 18:
     print('You are quite young')


来源:https://stackoverflow.com/questions/33977659/how-do-i-compare-a-string-and-an-integer-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!