How to break out of multiple loops?

后端 未结 30 3328
情书的邮戳
情书的邮戳 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条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 06:25

    Introduce a new variable that you'll use as a 'loop breaker'. First assign something to it(False,0, etc.), and then, inside the outer loop, before you break from it, change the value to something else(True,1,...). Once the loop exits make the 'parent' loop check for that value. Let me demonstrate:

    breaker = False #our mighty loop exiter!
    while True:
        while True:
            if conditionMet:
                #insert code here...
                breaker = True 
                break
        if breaker: # the interesting part!
            break   # <--- !
    

    If you have an infinite loop, this is the only way out; for other loops execution is really a lot faster. This also works if you have many nested loops. You can exit all, or just a few. Endless possibilities! Hope this helped!

提交回复
热议问题