我是 Python 的新手。
当我在输入中输入一个字母时,我写了这个并得到了这个错误:
TypeError: unorderable types: str() >= int()
这是我写的代码:
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 = int(input('How old are you?: '))
因此当您明确地将输入转换为 int 时,它总是会尝试将输入转换为整数,并且会在您输入无法转换为整数的字符串时引发 ValueError诠释。要处理这些情况,请执行以下操作:
except ValueError:
print('That is not a number')
所以,完整的解决方案可能如下所示:
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')