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

柔情痞子 提交于 2019-12-03 13:27:18

问题


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.


回答1:


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)



回答2:


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:


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


来源:https://stackoverflow.com/questions/12828771/how-to-go-back-to-first-if-statement-if-no-choices-are-valid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!