Python 代码似乎忽略了 ValueError

Python code seems to be ignoring ValueError

我想处理可能因用户输入无效而导致的 ValueErrors,但我仍然在控制台中收到红色错误,而不是程序按预期打印 'Invalid entry'。我不确定出了什么问题。

input_number = input("How many numbers would you like the program to calculate the average of?\n>> ")
try:
    input_number = int(input_number)
except ValueError:
    print("Invalid entry")

for i in range(input_number):
    input("Please enter a whole number (%i/%i numbers entered):\n>> " % (i + 1, input_number))

它似乎忽略了我的 try except 语句,因为错误出现在 for 语句的行上,说“TypeError:'str' object cannot be interpreted as an integer”。即使我将 except 修改为“除了 ValueError 或 TypeError”,它仍然不起作用。

子句应该是

except (ValueError, TypeError):
    ...

问题是,当您捕捉到 ValueError 时,您没有做任何事情来修复 input_number(即,使其成为 int),因此程序会继续经过您try 语句并进入您的 range() 调用,该调用继续引发另一个异常,因为 input_number 不是 int.

简单地捕获异常并不能修复导致它首先被引发的错误。如果你捕获异常,你需要理解它为什么被引发,并做一些适当的事情来纠正这种情况;盲目地捕获异常通常只会导致程序稍后出现另一个错误,就像这里所做的那样。

纠正这种情况的一种方法是再次提示用户:

while True:
    try:
        input_number = int(input(
            "How many numbers would you like the program to calculate the average of?\n>> "
        ))
        break
    except ValueError:
        print("Invalid entry")

使用上面的代码,循环继续直到 input_number 是一个 int.

因为看起来你会想要再次这样做,我建议把它放在一个函数中:

def input_number(prompt: str) -> int:
    """Prompt for a number until a valid int can be returned."""
    while True:
        try:
            return int(input(prompt))
        except ValueError:
            print("Invalid entry")

n = input_number(
    "How many numbers would you like the program to calculate the average of?\n>> "
)
numbers = [
    input_number(f"Please enter a whole number ({i}/{n} numbers entered):\n>>")
    for i in range(1, n+1)
]
print(f"Average: {sum(numbers)/len(numbers)}")
How many numbers would you like the program to calculate the average of?
>> I don't know
Invalid entry
How many numbers would you like the program to calculate the average of?
>> 4
Please enter a whole number (1/4 numbers entered):
>>5
Please enter a whole number (2/4 numbers entered):
>>42
Please enter a whole number (3/4 numbers entered):
>>???
Invalid entry
Please enter a whole number (3/4 numbers entered):
>>543
Please enter a whole number (4/4 numbers entered):
>>0
Average: 147.5