Skip to content Skip to sidebar Skip to footer

Valueerror: Invalid Literal For Int() With Base 10 -- How To Guard Against Invalid User Input?

I made a program where the user enters a number, and the program would count up to that number and display how much time it took. However, whenever I enter letters or decimals (i.e

Solution 1:

Well, there really a way to 'fix' this, it is behaving as expected -- you can't case a letter to an int, that doesn't really make sense. Your best bet (and this is a pythonic way of doing things), is to simply write a function with a try... except block:

defget_user_number():
    i = input("Enter a number.\n")
    try:
        # This will return the equivalent of calling 'int' directly, but it# will also allow for floats.returnint(float(i)) 
    except ValueError:
        #Tell the user that something went wrongprint("I didn't recognize {0} as a number".format(i))
        #recursion until you get a real numberreturn get_user_number()

You would then replace these lines:

z = input("Enter a number.\n")
z = int(z)

with

z = get_user_number()

Solution 2:

Try checking

if string.isdigit(z):

And then executing the rest of the code if it is a digit.

Because you count up in intervals of one, staying with int() should be good, as you don't need a decimal.

EDIT: If you'd like to catch an exception instead as wooble suggests below, here's the code for that:

try: 
    int(z)
    do something
except ValueError:
    do something else

Post a Comment for "Valueerror: Invalid Literal For Int() With Base 10 -- How To Guard Against Invalid User Input?"