Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 794
wondergoat77 Avatar asked Oct 10 '12 21:10

wondergoat77


2 Answers

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)
like image 124
Andrew Clark Avatar answered Nov 15 '22 14:11

Andrew Clark


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)
like image 32
Abhishek Bhatia Avatar answered Nov 15 '22 14:11

Abhishek Bhatia