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
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
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
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
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
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!