首页 > 解决方案 > 如何在两个数字之间进行输入

问题描述

我想强制用户输入在两个数字之间,例如 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

标签: python

解决方案


Use if-else to check if the value is within the required range or not if yes then assign it to the race_length

if not ask user to enter again.

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

推荐阅读