The Python Oracle

How can I break out of multiple loops?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game Looping

--

Chapters
00:00 Question
00:35 Accepted answer (Score 706)
00:51 Answer 2 (Score 467)
01:47 Answer 3 (Score 179)
02:19 Answer 4 (Score 149)
03:11 Thank you

--

Full question
https://stackoverflow.com/questions/1896...

Answer 1 links:
[Why does python use 'else' after for and while loops?]: https://stackoverflow.com/questions/9979...
[By definition]: https://stackoverflow.com/a/9980752/6739...

Answer 2 links:
[PEP 3136]: http://www.python.org/dev/peps/pep-3136/
[rejected it]: http://mail.python.org/pipermail/python-...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #nestedloops #break #controlflow

#avk47



ACCEPTED ANSWER

Score 744


My first instinct would be to refactor the nested loop into a function and use return to break out.




ANSWER 2

Score 512


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.




ANSWER 3

Score 186


PEP 3136 proposes labeled break/continue. Guido rejected it because "code so complicated to require this feature is very rare". The PEP does mention some workarounds, though (such as the exception technique), while Guido feels refactoring to use return will be simpler in most cases.




ANSWER 4

Score 164


First, ordinary logic is helpful.

If, for some reason, the terminating conditions can't be worked out, exceptions are a fall-back plan.

class GetOutOfLoop( Exception ):
    pass

try:
    done= False
    while not done:
        isok= False
        while not (done or isok):
            ok = get_input("Is this ok? (y/n)")
            if ok in ("y", "Y") or ok in ("n", "N") : 
                done= True # probably better
                raise GetOutOfLoop
        # other stuff
except GetOutOfLoop:
    pass

For this specific example, an exception may not be necessary.

On other other hand, we often have "Y", "N" and "Q" options in character-mode applications. For the "Q" option, we want an immediate exit. That's more exceptional.