Repeat user input in Python script

I am trying to figure out if there is a way to "force" the Python script not to "throw me" into the bash environment if I make a simple mistake in my Python script.

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

How can you tell Python to NOT 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.'

      

Please note that my last two lines are commented out. If I uncomment them, I obviously get the corresponding print statement and the program succeeds. However, suppose I didn't have those last two lines, and wanted MWE.py to "stay in Python mode" (so to speak) and not rudely return me to the bash shell, thus forcing me to repeat the scratch with python MWE.py

.

Is there a way to do this somehow?

Obviously this is a trivial MWE, but I'm trying to figure out the principle: is it possible to just return the last prompt that was presented to me right before I made an input error (for example, it was captured in this MWE when I pressed 3). Is there a generalized way to go back to x = raw_input("Please input a number 1 or 2: ")

(or something else the very last prompt I was given before I made a typing error)?

This is especially important in programs that require multiple user inputs at different stages. I would not want to start all over again.

+3


source to share


1 answer


It's called a loop (no parentheses around the conditions are 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 to write this. You should pay attention to how you initialize x

before the loop None

is typical of python.



Also note that the value x

is a string, not int

.

This would quickly become cumbersome if you had a large number of possible values ​​to test. So an alternative approach is to use an infinite loop and break

out when the answer is correct:

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"

      

+6


source







All Articles