我正在尝试编写一个程序来确定一个人的人生阶段,无论这个人是婴儿、 child 、青少年、成人还是老人。该程序以一个包含 input()
函数的变量开始,该函数允许用户输入年龄,以便程序可以开始运行。
问题是当我输入年龄大于99时,程序提示输入的年龄是婴儿。所以基本上,根据计划,123 岁的人是婴儿,这没有道理。
age=input("enter the person's age: ")
if age<'2':
print('the person is a baby')
elif age=='2' and age<'4':
print('the person is a toddler')
elif age >='4' and age<'13':
print ('the person is a kid')
elif age>='13' and age<'20':
print('the person is a teenager')
elif age>='20' and age<'65':
print('the person is an adult')
elif age>='65':
print('the person is an elder')
我想知道我的代码是否有误,尽管在我看来这很简单。无论如何,我猜我缺少一些理论知识,如果是这样的话,如果你们能对整个问题有所了解,我将不胜感激。
最佳答案
您实际上在这里所做的是比较字符串,这些字符串不会转化为您正在寻找的行为。您需要先将输入转换为 int()
。
如果您知道输入的格式保证正确,请使用:
age = int(input("enter the person's age: "))
然而,没有人是完美的,所以最好用 try-except 包裹起来:
age = input("enter the person's age: ")
try:
age = int(age)
except:
# Handle exception
if age < 2:
# Do something
elif ...
# Do more stuff
关于python - 当我处理大于 99 的数字时,我的代码开始产生不合逻辑的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57502840/