开始学习编码。我希望我的程序询问用户的年龄,然后对他们进行分类,我知道input()总是接收一个字符串值,所以我必须转换它。一开始我想我可以只做一次,就像这样:
print ('Enter your age:')
age = input ()
int(age)然后将age值与其他int值进行比较:
if age <18:
print ('Underage')
elif age >= 18 and age <30:
print ('young')但我一直收到这个错误: TypeError:'<‘在'str’和'int‘的实例之间不受支持
可以通过执行以下操作来修复它:
print ('Enter your age:')
age = input ()
if int(age) <18:
print ('Underage')
elif int(age) >= 18 and int(age) <30:
print ('young')但我想知道是否有一种方法可以不重复相同的事情。
谢谢您:)
发布于 2019-11-12 10:13:28
赋值变量时,强制转换为int
print ('Enter your age:')
# here
age = int(input ())
if age <18:
print ('Underage')
elif age >= 18 and int(age) <30:
print ('young')发布于 2019-11-12 10:14:00
这里可能做的两个小改进是,只将字符串年龄输入转换为整数一次。此外,if-else逻辑也可以简化:
print ('Enter your age:')
inp = input()
age = int(inp)
if age < 18:
print ('Underage')
elif age < 30: # age must be >= 18 already
print ('young')
else:
print('old')请注意,这里不需要范围检查,因为如果if条件失败,这意味着年龄必须已经大于18岁。
https://stackoverflow.com/questions/58811017
复制相似问题