Greenhill Greenhill - 7 months ago 19
Python Question

How do I avoid error while using int()?

I have a question concerning

int()
. Part of my Python codes looks like this

string = input('Enter your number:')
n = int(string)
print n


So if the input string of
int()
is not a number, Python will report ValueError and stop running the remaining codes.

I wonder if there is a way to make the program re-ask for a valid string? So that the program won't just stop there.

Thanks!

Answer Source

What you're looking for is

Try / Except

How it works:

try:
    # Code to "try".
except:
    # If there's an error, trap the exception and continue.
    continue

For your scenario:

def GetInput():
    try:
        string = input('Enter your number:') 
        n = int(string) 
        print n
    except:
        # Try to get input again.
        GetInput()