I want to handle possible ValueErrors resulting from invalid user input but I still get the red errors in the console instead of the program printing 'Invalid entry' as I intended. I'm not sure what's going wrong.
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))
It seems to ignore my try except statement as the error appears on the line of the for statement, saying "TypeError: 'str' object cannot be interpreted as an integer". It still doesn't work even if I amend the except to be "except ValueError or TypeError".
CodePudding user response:
The problem is that when you catch the ValueError
, you don't do anything to fix input_number
(i.e. make it an int
), so the program continues past your try
statement and into your range()
call, which proceeds to raise another exception because input_number
isn't an int
.
Simply catching an exception doesn't fix the error that caused it to be raised in the first place. If you catch an exception, you need to understand why it raised, and do something appropriate to correct the situation; blindly catching an exception will often just lead to another error later in your program, as it did here.
One way to correct this situation is to prompt the user again:
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")
With the above code, the loop continues until input_number
is an int
.
Since it looks like you'll be wanting to do this again, I'd suggest putting it in a function:
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
CodePudding user response:
The clause should be
except (ValueError, TypeError):
...