我正在进行一个简单的python练习,在这个练习中我会问一系列问题并从用户那里获得输入。我用";输入您的年龄";如果用户输入年龄的字母值而不是int,我希望程序继续运行,而不是损坏,因为我将转换为int来计算年龄是否小于18或大于18,以及年龄是否在特定年龄之间。我无法将字母转换为整数
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
使用try/except。
age = input("Please enter your age: ")
try:
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
except:
print("Please enter a number")
如果int转换失败,代码将跳转到exception,而不是崩溃。
如果你想让用户重试,你可以写这样的东西。注意你使用的范围和负数。
age = input("Please enter your age: ")
ageNum = 0
while(ageNum <= 0):
try:
ageNum = int(age)
if (ageNum) < 18 or ageNum > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
elif ...
except:
print("Please enter a valid number")
我会使用while循环,例如
while int(age) != age:
input("Age must be an integer.nPlease try again.")
正如@Barmar所说,你需要检查你的if语句。