Home >Backend Development >Python Tutorial >How Can I Ensure Valid User Input in My Program?
Requesting User Input Until a Valid Response is Provided
In programming, it's crucial to ensure user input is valid before proceeding with further operations. If invalid data is accepted, it can lead to incorrect results or program crashes. Let's explore effective techniques for handling user input validation and preventing errors.
Exceptions and Looping
One approach is to use try and except blocks to catch errors that may arise when parsing user input. By wrapping the input-parsing operation inside a while loop, you can continuously request input until it meets the desired criteria.
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") continue else: break
Custom Validation Logic
In addition to exception handling, you can implement your own validation rules to check against the input. For instance, you may reject values that are negative or outside a specific range.
while True: data = input("Pick an answer from A to D:") if data.lower() not in ('a', 'b', 'c', 'd'): print("Not an appropriate choice.") else: break
Error Handling for All Cases
For comprehensive input validation, you can combine exception handling with custom rules in a single loop. This ensures that both parse errors and invalid values are detected and handled appropriately.
while True: try: age = int(input("Please enter your age: ")) except ValueError: print("Sorry, I didn't understand that.") continue if age < 0: print("Sorry, your response must not be negative.") continue else: break
Encapsulation and Reusable Functions
If you frequently encounter the need for user input validation, it's beneficial to encapsulate the relevant code into a separate function. This allows for code reuse and simplifies the input-gathering process.
def get_non_negative_int(prompt): while True: value = int(input(prompt)) if value >= 0: break return value age = get_non_negative_int("Please enter your age: ")
Extensibility and Generic Input Validation
By extending the concept further, you can create a highly versatile input-validation function that covers a wide range of requirements.
def sanitised_input(prompt, type_=None, min_=None, max_=None, range_=None): while True: ui = input(prompt) try: if type_ is not None: ui = type_(ui) except ValueError: continue # Perform further validation checks and return valid input if all criteria are met.
Common Pitfalls and Best Practices
The above is the detailed content of How Can I Ensure Valid User Input in My Program?. For more information, please follow other related articles on the PHP Chinese website!