warship
warship

Reputation: 3024

Retry user input in Python script

I'm trying to figure out if there is a way to "force" a Python script to not "throw me back" into the bash environment if I commit a simple error in my Python script.

Here's an MWE (MWE.py) to illustrate the point:

How can you tell Python NOT to kick me out of the program if I press 3 in the MWE below?

x = raw_input("Please input a number 1 or 2: ")
if (x == '1'):
    print '1'
elif (x == '2'):
    print '2'
#else:
    #print 'Neither 1 nor 2.'

Notice that my last two lines are commented out. If I uncomment them, obviously I will get the respective print statement and the program will finish successfully. However, let's assume that I didn't have those last two lines, and wanted MWE.py to "stay in Python mode" (so to speak) and not harshly return me to the bash shell, thereby forcing me to rerun from scratch with python MWE.py.

Is there a way to accomplish this somehow?

Obviously, this is a trivial MWE but I'm trying to understand the principle: is it possible to just return the last prompt that I was presented with right before I committed an input error (such as committed in this MWE when I pressed 3). Is there basically a "generalized way" to get back to x = raw_input("Please input a number 1 or 2: ") (or whatever else was the most recent prompt that I was given before I made an input error)?

This seems particularly important in programs that require multiple user inputs at different stages. I would hate to start all over.

Upvotes: 3

Views: 4603

Answers (1)

cdarke
cdarke

Reputation: 44354

It's called a loop (the parentheses around the conditions are not required):

x = None

while x != '1' and x != '2':
    x = raw_input("Please input a number 1 or 2: ")
    if x == '1':
        print '1'
    elif x == '2':
        print '2'
    else:
        print 'Neither 1 nor 2.'

print "all OK"

There are many ways of writing this. You should pay attention to how you initialise x before the loop, None is typical in python.

Also note the the value of x is a string, not an int.

This would quickly become unwieldy if you had a large number of possible values to test. So an alternative approach is to use an infinite loop and break out on a correct reply:

x = None

while True:
    x = raw_input("Please input a number 1 or 2: ")
    if x == '1':
        print '1'
        break
    elif x == '2':
        print '2'
        break
    else:
        print 'Invalid input, try again'

print "all OK"

Upvotes: 6

Related Questions