How to break out of multiple loops?

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

    Here's another approach that is short. The disadvantage is that you can only break the outer loop, but sometimes it's exactly what you want.

    for a in xrange(10):
        for b in xrange(20):
            if something(a, b):
                # Break the inner loop...
                break
        else:
            # Continue if the inner loop wasn't broken.
            continue
        # Inner loop was broken, break the outer.
        break
    

    This uses the for / else construct explained at: Why does python use 'else' after for and while loops?

    Key insight: It only seems as if the outer loop always breaks. But if the inner loop doesn't break, the outer loop won't either.

    The continue statement is the magic here. It's in the for-else clause. By definition that happens if there's no inner break. In that situation continue neatly circumvents the outer break.

提交回复
热议问题