如何验证变量是否在两个指定的数字之间?

时间:2015-02-20 10:36:53

标签: python validation

如何验证用户输入以限制它们仅输入介于-5和-21之间的数值?我目前有这个while循环设置;

while True: 
 if flatNumber.isdigit():
      flatNumber = int(flatNumber)
      if flatNumber>5 and flatNumber<21: 
           print("Enjoy your stay.") 
           break 
      else:  
           flatNumber = input("Please enter your flat number.")
 else: 
    flatNumber = input("Please enter a numerical flat number.")

然而,这仅验证5到21之间的数值?有人可以发布一个解决方案并解释它如何验证-5和-21之间的数值?

5 个答案:

答案 0 :(得分:2)

您可以使用负值进行简化的链式比较:

if -21 < flatNumber < -5:

str.isdigit无法为负数工作,除了验证输入时,您几乎应该总是使用try /

while True:
    try: 
        # try to cast to int
        flatNumber = int(input("Please enter your flat number."))
        # if cast was successful make sure it is in range if not ask again
        if not -21 < flatNumber < -5:
            print("Not in range -5 to -21")
            continue
        break # else all is good break the loop
    except ValueError:
           print("Invalid input")

print(flatNumber)

答案 1 :(得分:1)

你能改变不平等的数字和方向吗?像这样:

if flatNumber<-5 and flatNumber>-21:

答案 2 :(得分:0)

如果你想要像你这样的独家测试+5到+21:

if flatNumber<-5 and flatNumber>-21: 
           print("Enjoy your stay.") 
           break 
      else:

如果你想要包容性测试

if flatNumber<=-5 and flatNumber>=-21: 
           print("Enjoy your stay.") 
           break 
      else:

答案 3 :(得分:0)

如果flatNumber&gt; -21和flatNumber&lt; -5:

请记住,-5大于-21。

答案 4 :(得分:0)

修改此行,如

if flatNumber<-5 and flatNumber>-21: