Skip to content Skip to sidebar Skip to footer

Catching Error On Input Validation

I need to add an error message if the user enters a string instead of an integer in my menu selection, and also amounts that the user input as data. I tried this code but it doesn'

Solution 1:

That's because passing an invalid string (not a number) to int() will raise a ValueError, and not TypeError. You're close though.

Just change it and it should work great.

except ValueError:
    print('Error!')

If you want to do something with the newamount variable, i suggest you to do it in the try block:

try:
    newamount=int(input('Enter the new amount:'))
    tempfunction = amount + newamount

Hope this helps!

Solution 2:

TypeError would be raised if the parameter to int() was of the wrong type.

Assuming you are using Python3, the return value of input() will always be type str

ValueError is raised if the type is ok, but the content isn't able to be converted to an int.

To ask over and over, you should use a while loop

whileTrue:
    try:
        newamount=int(input('Enter the new amount:'))
        breakexcept ValueError:
        print ("error")

If you want to keep count of the errors, use itertools.count and a for loop

from itertools import count
for c in count():
    try:
        newamount=int(input('Enter the new amount:'))
        breakexcept ValueError:
        print ("error", c)

Solution 3:

I think its better to use raw_input in these cases where the input is to be eval manually. It goes like this...

s = raw_input()
try:
    choice = int(s)
except ValueError:
print ('Wrong Input!')  

Post a Comment for "Catching Error On Input Validation"