How to go back to first if statement if no choices are valid

wondergoat77 picture wondergoat77 · Oct 10, 2012 · Viewed 53.7k times · Source

How can I have Python move to the top of an if statement if no condition is satisfied correctly.

I have a basic if/else statement like this:

print "pick a number, 1 or 2"
a = int(raw_input("> ")

if a == 1:
    print "this"
if a == 2:
    print "that"
else:
   print "you have made an invalid choice, try again."

What I want is to prompt the user to make another choice for this if statement without them having to restart the entire program, but am very new to Python and am having trouble finding the answer online anywhere.

Answer

Andrew Clark picture Andrew Clark · Oct 10, 2012

A fairly common way to do this is to use a while True loop that will run indefinitely, with break statements to exit the loop when the input is valid:

print "pick a number, 1 or 2"
while True:
    a = int(raw_input("> ")
    if a == 1:
        print "this"
        break
    if a == 2:
        print "that"
        break
    print "you have made an invalid choice, try again."

There is also a nice way here to restrict the number of retries, for example:

print "pick a number, 1 or 2"
for retry in range(5):
    a = int(raw_input("> ")
    if a == 1:
        print "this"
        break
    if a == 2:
        print "that"
        break
    print "you have made an invalid choice, try again."
else:
    print "you keep making invalid choices, exiting."
    sys.exit(1)