2
print("how old are you")
age = input(">")
if age >= 24:
print("you are getting old")
print (age)
else:
print("i don't care")
print (age)

这是我得到的错误:

if age >= 24:
TypeError: unorderable types:     str() >= int()
4

2 回答 2

8

在 Python 3 上,input() 总是返回一个字符串值。使用int()类型来转换它:

if int(age) >= 24:

字符串值和 int 不可排序:

>>> '24' > 23
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()

请注意,如果输入无法转换,则int()可能会引发异常:ValueError

>>> int('Why do you want to know my age?')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Why do you want to know my age?'
于 2013-08-15T21:45:48.263 回答
3

age是一个字符串,而不是一个 int。要使其成为 int,请使用该int()函数,因此:

print("how old are you")
age = input(">")
if int(age) >= 24:
    print("you are getting old")
    print (age)
...

注意这一行:

if int(age) >= 24:
于 2013-08-15T21:46:04.630 回答