How to break out of multiple loops?

后端 未结 30 3244
情书的邮戳
情书的邮戳 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:00

    To break out of multiple nested loops, without refactoring into a function, make use of a "simulated goto statement" with the built-in StopIteration exception:

    try:
        for outer in range(100):
            for inner in range(100):
                if break_early():
                    raise StopIteration
    
    except StopIteration: pass
    

    See this discussion on the use of goto statements for breaking out of nested loops.

提交回复
热议问题