You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为输入数据添加条件语句及范围校验并抛出异常?

How to Add Conditional Input Validation with Exception Handling in Python

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-except block to catch both non-integer inputs (which naturally throw ValueError) and our custom range violation error.
  • The conditional check (-20 <= num <= 20) verifies the input is within bounds. If not, we explicitly raise a ValueError with 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 10:22:45