Home > Backend Development > Python Tutorial > How to Ensure Valid User Input in Python?

How to Ensure Valid User Input in Python?

Barbara Streisand
Release: 2025-01-02 17:01:40
Original
301 people have browsed it

How to Ensure Valid User Input in Python?

Asking for Valid User Input Until Received

When requesting user input, it's crucial to handle invalid responses gracefully rather than crashing or accepting incorrect values. The following techniques ensure valid input is obtained:

Try/Except for Exceptional Input

Use try/except to catch specific input that cannot be parsed. For instance:

while True:
    try:
        age = int(input("Please enter your age: "))
    except ValueError:
        print("Sorry, that's not a valid age.")
        continue
    break
Copy after login

Custom Validation for Additional Rules

Sometimes, input that can be parsed may still not meet certain criteria. You can add custom validation logic to reject specific values:

while True:
    data = input("Enter a positive number: ")
    if int(data) < 0:
        print("Invalid input. Please enter a positive number.")
        continue
    break
Copy after login

Combining Exception Handling and Custom Validation

Combine both techniques to handle both invalid parsing and custom validation rules:

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
Copy after login

Encapsulation in a Function

To reuse the custom input validation logic, encapsulate it in a function:

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
Copy after login

Advanced Input Sanitization

You can create a more generic input function to handle various validation scenarios:

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
Copy after login

This function enables you to specify the data type, range, and other constraints for the user input.

The above is the detailed content of How to Ensure Valid User Input in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template