且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2021-10-22 21:57:55

您可以添加简单的if语句,如果数字不在范围内,则会引发错误。您期望

You could add in a simple if statement and raise an Error if the number isn't within the range you're expecting

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