如何在两个数字之间进行输入

时间:2019-04-25 04:39:29

标签: python

我想强制用户输入介于两个数字之间,例如5-15,如果它们之间的数字也不相等,请输入这两个数字之间的一个数字,然后请求其他输入。

我已经有一个输入,强迫您输入一个整数。

while True:

 try:
    # asking for race length
    race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15)"))
except ValueError:
    print("Sorry, I didn't understand that.")
    #if an interger isn't entered do loop above to avoid and error
    continue
else:
    #race length succesfully found
    #finished the loop
    break

2 个答案:

答案 0 :(得分:1)

使用if-else检查值是否在所需范围内,如果是,则将其分配给 race_length

如果不要求用户再次输入。

if(x>5 and x<15):
   race_length  = x
else:
   input('Choose the Length You Would Like You Race To Be (Between 5 and 15)')

答案 1 :(得分:0)

您可以使用assert <bool>并处理AssertionError来引发错误 请参阅以下代码,

while True:
    try:
        race_length = int(input("Choose the Length You Would Like You Race To Be (Between 5 and 15) : "))
        assert 5 < race_length < 15
    except ValueError:
        print("Sorry, I didn't understand that.")
    except AssertionError:
        print("Please Enter a number between 5 and 15")
    else:
        break
相关问题