检查用户输入(Python)的问题
我试图检查用户输入是否为整数,以及下限是否大于或等于零。我还试图检查上界是否大于下界。这是我的代码:检查用户输入(Python)的问题,python,error-handling,user-input,Python,Error Handling,User Input,我试图检查用户输入是否为整数,以及下限是否大于或等于零。我还试图检查上界是否大于下界。这是我的代码: while True: try: lower_bound = int(input("What is the lower bound for x >= 0 (inclusive?)")) except ValueError: print("Lower bound is not an integer.") continue
while True:
try:
lower_bound = int(input("What is the lower bound for x >= 0 (inclusive?)"))
except ValueError:
print("Lower bound is not an integer.")
continue
else:
if lower_bound < 0:
print("Lower bound cannot be less than zero.")
continue
try:
upper_bound = int(input("What is the upper bound (inclusive)?"))
break
except ValueError:
print("Upper bound is not an integer.")
else:
if (upper_bound < lower_bound):
print("The upper bound cannot be less than the lower bound.")
continue
为True时:
尝试:
下限=int(输入(“x>=0(含)的下限是多少”)
除值错误外:
打印(“下限不是整数。”)
持续
其他:
如果下限<0:
打印(“下限不能小于零。”)
继续
尝试:
上限=int(输入(“上限是多少(包括)?”)
打破
除值错误外:
打印(“上限不是整数。”)
其他:
如果(上界<下界):
打印(“上限不能小于下限。”)
持续
正如检查用户输入的下限值一样,检查上限值是否为整数也是如此。但是,如果上界小于下界,则不会返回错误-这是为什么
另外,我觉得我的代码必须非常冗长——我怎样才能使所有这些错误检查更加简洁呢
谢谢
本
你为什么要分手?此中断
将立即结束循环,跳过上限<下限
检查。在最后一次检查后移动中断
,这样它只会在所有检查通过后中断。因为我是个白痴?:)如果您能就如何减少代码的冗长性提出建议,我们将不胜感激。
upper_bound = int(input("What is the upper bound (inclusive)?"))
break