如何在Python中比较字符串和整数?

Ker*_*tto 3 python string int input

我是Python的新手。我写了这个,当我在输入中输入字母时出现了这个错误:

TypeError: unorderable types: str() >= int()
Run Code Online (Sandbox Code Playgroud)

这是我编写的代码:

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')
Run Code Online (Sandbox Code Playgroud)

Ahs*_*que 7

你应该做:

user_input = int(input('How old are you?: '))
Run Code Online (Sandbox Code Playgroud)

因此,当您将输入明确转换为int时,它将始终尝试将输入转换为整数,并且在您输入字符串而不是int时会引发valueError。要处理这些情况,请执行以下操作:

except ValueError:
    print ('That is not a number')
Run Code Online (Sandbox Code Playgroud)

因此,完整的解决方案可能如下所示:

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')
Run Code Online (Sandbox Code Playgroud)