How to break out of multiple loops?

后端 未结 30 3383
情书的邮戳
情书的邮戳 2020-11-21 05:48

Given the following code (that doesn\'t work):

while True:
    #snip: print out current state
    while True:
        ok = get_input(\"Is this ok? (y/n)\")
          


        
30条回答
  •  Happy的楠姐
    2020-11-21 06:09

    There is a hidden trick in the Python while ... else structure which can be used to simulate the double break without much code changes/additions. In essence if the while condition is false, the else block is triggered. Neither exceptions, continue or break trigger the else block. For more information see answers to "Else clause on Python while statement", or Python doc on while (v2.7).

    while True:
        #snip: print out current state
        ok = ""
        while ok != "y" and ok != "n":
            ok = get_input("Is this ok? (y/n)")
            if ok == "n" or ok == "N":
                break    # Breaks out of inner loop, skipping else
    
        else:
            break        # Breaks out of outer loop
    
        #do more processing with menus and stuff
    

    The only downside is that you need to move the double breaking condition into the while condition (or add a flag variable). Variations of this exists also for the for loop, where the else block is triggered after loop completion.

提交回复
热议问题