如何在python中使用输入比较符号

如何在python中使用输入比较符号,python,Python,我正在尝试制作一个程序,它将响应某人的年龄,但我不知道如何使用比较符号。这是我试图运行的代码 age = input('How old are you? \n >>') if (age < 20): print('Hey you are pretty young.') if (age > 20): print('wow you are pretty old') age=input('您几岁?\n>>')) 如果(年龄20岁): 打印(‘哇,你真老了’)

我正在尝试制作一个程序,它将响应某人的年龄,但我不知道如何使用比较符号。这是我试图运行的代码

age = input('How old are you? \n >>')
if (age < 20):
    print('Hey you are pretty young.')
if (age > 20):
    print('wow you are pretty old')
age=input('您几岁?\n>>'))
如果(年龄<20岁):
打印(“嘿,你很年轻。”)
如果(年龄>20岁):
打印(‘哇,你真老了’)
但是当我试着运行它时,我得到了这个错误

Traceback (most recent call last):
  File "C:/Users/Daniel/Desktop/Computer science/week 6/age.py", line 2, in <module>
    if (age < 20):
TypeError: '<' not supported between instances of 'str' and 'int'
回溯(最近一次呼叫最后一次):
文件“C:/Users/Daniel/Desktop/Computer science/week 6/age.py”,第2行,在
如果(年龄<20岁):

TypeError:“作为输入得到的是一个字符串,需要将其转换为int,然后才能进行比较:

age = int(input('How old are you? \n >>'))
最好添加一些错误处理,例如:

try:
    age = int(input('How old are you? \n >>'))

except ValueError as ex:
    print("Not a valid age.")

age
是一个
str
,您无法将
str
对象与
int
对象进行比较…错误消息是否不够清楚?这是否回答了您的问题?我已经接受了答案。而且这真的不一样@B.GoThanks Jan!我需要它。@jamylak age=float(输入(“输入任何数字”)@B.Go:我敢肯定,jamylak在这里开了个玩笑。