'Python code seems to be ignoring ValueError
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".
Solution 1:[1]
The clause should be
except (ValueError, TypeError):
...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ti7 |
