首页 >后端开发 >Python教程 >Python中如何确保用户输入有效?

Python中如何确保用户输入有效?

Barbara Streisand
Barbara Streisand原创
2025-01-02 17:01:40304浏览

How to Ensure Valid User Input in Python?

请求有效的用户输入直至收到

请求用户输入时,优雅地处理无效响应而不是崩溃或接受不正确的值至关重要。以下技术可确保获得有效的输入:

尝试/排除异常输入

使用 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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn