如何接受Python中int转换的字符串字母输入?

How to accept String letter Input from int conversion in Python?

我正在做一个简单的 python 练习,我会问一系列问题并从用户那里获得输入。我提示用户“输入您的年龄”,如果用户输入年龄的字母值而不是 int,我希望程序继续而不是损坏,因为如果年龄小于 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.

我会使用 while 循环,例如

while int(age) != age:
    input("Age must be an integer.\nPlease try again.")

正如@Barmar 所说,您需要检查您的 if 语句。

使用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 转换失败,代码将跳转到 except 而不是崩溃。

如果你想让用户重试,你可以这样写。请注意您使用的范围和负数。

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")