在 Python 中,用户输入验证是一项重要的任务。它可以防止用户输入无效或非法的数据,从而导致程序崩溃或产生错误结果。在下面的代码中,用户被要求输入两个整数:lower_bound 和 upper_bound,并检查这两个整数是否满足以下条件:
- lower_bound 是一个非负整数。
- upper_bound 是一个整数。
- upper_bound 不小于 lower_bound。
如果用户输入的整数不满足这些条件,程序会打印错误信息并继续提示用户输入。
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
然而,当用户输入 upper_bound 时,如果 upper_bound 小于 lower_bound,程序不会打印错误信息,而是继续执行循环。这是因为在尝试转换 upper_bound 为整数时,会抛出 ValueError 异常。但是,在该异常处理程序中,程序直接跳出循环,而没有进行任何错误检查。
2、解决方案
为了解决这个问题,需要将 break 语句移到所有错误检查之后。这样,只有当所有错误检查都通过时,程序才会跳出循环。
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)?"))
except ValueError:
print("Upper bound is not an integer.")
continue
else:
if (upper_bound < lower_bound):
print("The upper bound cannot be less than the lower bound.")
continue
break
现在,当用户输入 upper_bound 时,如果 upper_bound 小于 lower_bound,程序会打印错误信息并继续循环。
为了使代码更加简洁,可以将错误检查部分提取成一个单独的函数。
def check_input(lower_bound, upper_bound):
if not isinstance(lower_bound, int) or lower_bound < 0:
raise ValueError("Lower bound must be a non-negative integer.")
if not isinstance(upper_bound, int):
raise ValueError("Upper bound must be an integer.")
if upper_bound < lower_bound:
raise ValueError("Upper bound cannot be less than lower bound.")
return lower_bound, upper_bound
while True:
try:
lower_bound, upper_bound = check_input(lower_bound, upper_bound)
break
except ValueError as e:
print(e)
现在,代码更加简洁,而且易于理解。