如何验证用户输入以将其限制为仅输入-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之间的数值吗?

最佳答案

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

if -21 < flatNumber < -5:


str.isdigit不适用于负数,验证输入时,几乎应始终使用try / except:

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)

09-10 07:33