请求有效的用户输入直至收到
请求用户输入时,优雅地处理无效响应而不是崩溃或接受不正确的值至关重要。以下技术可确保获得有效的输入:
尝试/排除异常输入
使用 try/ except 捕获无法解析的特定输入。例如:
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, that's not a valid age.") continue break
附加规则的自定义验证
有时,可以解析的输入可能仍然不满足某些条件。您可以添加自定义验证逻辑来拒绝特定值:
while True: data = input("Enter a positive number: ") if int(data) < 0: print("Invalid input. Please enter a positive number.") continue break
结合异常处理和自定义验证
结合这两种技术来处理无效解析和自定义验证规则:
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, that's not a valid age.") continue if age < 0: print("Invalid age. Please enter a positive number.") continue break
封装在函数
要重用自定义输入验证逻辑,请将其封装在函数中:
def get_positive_age(): while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, that's not a valid age.") continue if age < 0: print("Invalid age. Please enter a positive number.") continue return age
高级输入清理
您可以创建一个更通用的输入函数来处理各种验证场景:
def get_valid_input(prompt, type_=None, min_=None, max_=None, range_=None): while True: try: value = type_(input(prompt)) except ValueError: print(f"Invalid input type. Expected {type_.__name__}.") continue if max_ is not None and value > max_: print(f"Value must be less than or equal to {max_}.") continue if min_ is not None and value < min_: print(f"Value must be greater than or equal to {min_}.") continue if range_ is not None and value not in range_: template = "Value must be {}." if len(range_) == 1: print(template.format(*range_)) else: expected = " or ".join(( ", ".join(str(x) for x in range_[:-1]), str(range_[-1]) )) print(template.format(expected)) else: return value
此函数使您能够指定用户输入的数据类型、范围和其他约束。
以上是Python中如何确保用户输入有效?的详细内容。更多信息请关注PHP中文网其他相关文章!