输入验证对于确保依赖用户的程序中准确收集数据至关重要相互作用。然而,在处理意外或无效数据时,验证用户输入可能具有挑战性。这可能会导致程序崩溃或不正确的结果。
最常见的方法是使用带有 try 和 except 块的 while 循环来处理解析时引发的异常输入。例如:
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Invalid input. Please enter a valid age:") continue else: break
如果您需要超出 Python 处理范围的更具体验证,您可以实现自定义逻辑:
while True: data = input("Please enter a loud message (must be all caps): ") if not data.isupper(): print("Input must be all caps. Please enter a loud message:") continue else: break
结合这两种解决方案提供了管理的灵活性不同的验证要求:
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Invalid input. Please enter a valid age:") continue if age < 0: print("Age cannot be negative. Please enter a valid age:") continue else: break
如果需要一致地验证多个输入,请考虑创建可重用函数:
def get_valid_input(prompt, type_=int, min_=None, max_=None, range_=None): while True: try: value = type_(input(prompt)) except ValueError: print("Invalid input. Please enter a valid value:") continue if min_ is not None and value < min_: print("Value must be greater than or equal to {}. Please enter a valid value:".format(min_)) continue elif max_ is not None and value > max_: print("Value must be less than or equal to {}. Please enter a valid value:".format(max_)) continue elif range_ is not None and value not in range_: print("Value must be in the range {}. Please enter a valid value:".format(range_)) continue else: return value
通过实现这些技术,您可以确保您的程序优雅地处理用户输入,防止崩溃并收集准确的数据。
以上是如何确保我的程序妥善处理无效的用户输入?的详细内容。更多信息请关注PHP中文网其他相关文章!