如何验证Python字典用户输入?里程表读数非数字时抛出异常
Hey there! Let's break down how to add proper input validation to your Python dictionary code so you can handle non-numeric inputs gracefully.
First, your current code uses int(input(...)) directly for odometer readings—this will throw a generic ValueError if someone enters text instead of a number, but it's not very user-friendly or explicit. Plus, your Model Year field is also a numeric value but isn't being validated at all! Here's how to fix that:
1. Create a Reusable Validation Function
A dedicated function to handle numeric input checks will make your code cleaner and easier to maintain. You can choose to either prompt the user to try again, or throw a custom exception (whichever fits your use case).
Option 1: Prompt for Retry (User-Friendly)
This version keeps asking for input until a valid number is provided:
def get_valid_numeric_input(prompt): while True: user_input = input(prompt) try: return int(user_input) except ValueError: print(f"Oops! '{user_input}' isn't a valid number. Please try again.") # Build your dictionary with validated inputs Auto_details = { 'Car brand': input('Car brand:'), 'Car model': input('Car model:'), 'Model Year': get_valid_numeric_input('Model Year:'), 'Starting odometer reading': get_valid_numeric_input('Starting odometer reading:'), 'Ending odometer reading': get_valid_numeric_input('Ending odometer reading:') }
Option 2: Throw a Custom Exception (For Strict Validation)
If you want to explicitly raise a meaningful error instead of retrying, define a custom exception class for clearer error handling:
# Custom exception to make errors more descriptive class InvalidNumericInputError(ValueError): """Raised when input is not a valid integer""" pass def get_valid_numeric_input(prompt): user_input = input(prompt) try: return int(user_input) except ValueError: field_name = prompt.strip(':') raise InvalidNumericInputError(f"Invalid input for '{field_name}': '{user_input}' is not a valid integer.") from None # Build the dictionary with validated inputs Auto_details = { 'Car brand': input('Car brand:'), 'Car model': input('Car model:'), 'Model Year': get_valid_numeric_input('Model Year:'), 'Starting odometer reading': get_valid_numeric_input('Starting odometer reading:'), 'Ending odometer reading': get_valid_numeric_input('Ending odometer reading:') }
Bonus: Add Extra Validation Rules
If you want to ensure odometer readings are positive (since you can't have negative miles!), you can extend the function:
def get_valid_numeric_input(prompt, allow_negative=False): while True: user_input = input(prompt) try: num = int(user_input) if not allow_negative and num < 0: print("Please enter a positive number.") continue return num except ValueError: print(f"Oops! '{user_input}' isn't a valid number. Please try again.")
Use it for odometer fields like this:
'Starting odometer reading': get_valid_numeric_input('Starting odometer reading:'),
Key Improvements
- Reusability: The validation function works for all numeric fields, so you don't repeat code.
- Clarity: Either users get a helpful prompt to correct their input, or your code throws a custom exception that clearly describes what went wrong (no more vague default errors).
- Flexibility: You can easily add more rules (like positive numbers) without rewriting validation logic for every field.
内容的提问来源于stack exchange,提问作者Chinyama

