How to go back to first if statement if no choices are valid
Asked Answered
P

3

12

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.

Promisee answered 10/10, 2012 at 21:34 Comment(3)
You'll have to wrap the whole thing in a loop (usually while).Mccartan
so while will do it for me? thanks ill go research, had no idea even where to startPromisee
@Mccartan It's times like these I miss the do-while loop, easy to emulate with a regular while loop thoughHammerlock
P
15

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)
Phoney answered 10/10, 2012 at 21:39 Comment(0)
Z
4

Use a while loop.

print "pick a number, 1 or 2"
a = None
while a not in (1, 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."
Zenobiazeolite answered 10/10, 2012 at 21:36 Comment(3)
thanks, you beat me to figuring it out myself and closing the question, appreciate the help thanksPromisee
Parentheses in line 2 are unnecessary and you missed the colon. Also would be easier to use while a not in (1, 2):.Battleplane
@RishabKurapati Please use the Edit Summary box properly.Clingy
A
4

You can use a recursive function

def chk_number(retry)
    if retry==1
        print "you have made an invalid choice, try again."
    a=int(raw_input("> "))
    if a == 1:
        return "this"
    if a == 2:
        return "that"
    else:
        return chk_number(1)

print "Pick a number, 1 or 2"
print chk_number(0)
Asphyxiate answered 10/10, 2012 at 21:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.