Python 输入验证:如何将用户输入限制为特定范围的整数?

Ric*_*all 0 python validation exception-handling exception input

初学者在这里,寻找有关输入验证的信息。

我希望用户输入两个值,一个必须是大于零的整数,下一个是 1-10 之间的整数。我已经看到很多输入验证函数对于这两个简单的情况似乎过于复杂,有人可以帮忙吗?

对于第一个数字(大于 0 的整数,我有):

while True:
    try:
        number1 = int(input('Number1: '))
    except ValueError:
        print("Not an integer! Please enter an integer.")
        continue
    else:
        break
Run Code Online (Sandbox Code Playgroud)

这也不会检查它是否为阳性,我希望它这样做。我还没有为第二个准备任何东西。任何帮助表示赞赏!

AK4*_*K47 5

您可以添加一个简单的 if 语句并在数字不在您期望的范围内时引发错误

while True:
    try:
        number1 = int(input('Number1: '))
        if number1 < 1 or number1 > 10:
            raise ValueError #this will send it to the print message and back to the input option
        break
    except ValueError:
        print("Invalid integer. The number must be in the range of 1-10.")
Run Code Online (Sandbox Code Playgroud)