How to return to the first if the statement is invalid

How can I get Python to move to the beginning of the if if the condition is not met correctly.

I have a basic if / else statement:

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." 

I want to invite the user to make another choice for this if statement, without having to restart the entire program, but I am very new to Python and it is difficult for me to find an answer on the Internet anywhere.

+6
source share
3 answers

A fairly general way to do this is to use the while True , which 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 good way to limit the number of attempts, 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) 
+6
source

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." 
+4
source

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) 
+3
source

Source: https://habr.com/ru/post/927396/


All Articles