如何为输入数据添加条件语句及范围校验并抛出异常?
Hey there! Let's modify your Python program to enforce that input numbers fall between -20 and 20, and throw an exception if they don't. Here are two practical approaches depending on how you want to handle invalid inputs:
Basic Approach: Raise Exception on Invalid Input
This version will immediately raise a clear ValueError when an input is out of range (or non-integer), which you can catch and handle as needed:
lst = [] print("Enter 10 numbers:\n") for i in range(10): try: num = int(input()) # Check if the number is within the valid range if not (-20 <= num <= 20): raise ValueError(f"Input {num} is invalid! Must be between -20 and 20 inclusive.") lst.append(num) except ValueError as e: print(f"Error: {e}") # Uncomment below to exit immediately on invalid input # exit(1) print("\nThe entered list is:", lst)
What's happening here:
- We use a
try-exceptblock to catch both non-integer inputs (which naturally throwValueError) and our custom range violation error. - The conditional check
(-20 <= num <= 20)verifies the input is within bounds. If not, we explicitly raise aValueErrorwith a descriptive message. - You can choose to exit the program right away with
exit(1)if you don't want to continue after an invalid entry, or let it proceed (though your list will have fewer than 10 elements in that case).
User-Friendly Approach: Retry Until Valid Input
If you want the program to keep asking for a valid number instead of crashing, add a while loop to retry until the user gets it right:
lst = [] print("Enter 10 numbers:\n") for i in range(10): while True: try: num = int(input(f"Enter number {i+1}: ")) if -20 <= num <= 20: lst.append(num) break # Move to next number once valid input is received else: print("Whoops! That number is out of range. Please enter between -20 and 20.") except ValueError: print("Invalid input! Please enter a whole number.") print("\nThe entered list is:", lst)
This version is much more forgiving for users. The while True loop will keep running until a valid integer within the range is entered, guiding the user to correct their input each time.
Key benefits:
- Handles both non-integer inputs and out-of-range values gracefully.
- Clear prompts help the user understand what's wrong.
- Ensures you end up with exactly 10 valid numbers in your list.
内容的提问来源于stack exchange,提问作者Manu Bharath Murali

