gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:14:46 25 4
gpt4 key购买 nike

如何验证用户输入以限制他们只能输入 -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)

关于python - 如何验证变量是否在两个指定数字之间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28626898/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com