It sounds like you want a "multi-level break", a statement that can break out of two or more loops at once.
Some languages have such a thing, but Python doesn't.
But there are a few things you can do instead, in order from the usually-best solution down to don't-ever-do-this.
Refactor this into a function. When you return
from a function, it breaks out of any loops you're in, all the way to the edge of the function.
Use a custom exception. For example, class BreakException(Exception): pass
. Then wrap a try:
/ except BreakException: pass
around the outer loop. Then just raise BreakException()
to break. When you raise
an exception, it breaks out of any loops you're in, all the way to the except
statement.
Use explicit flags to keep track of what you're doing. Put doublebreak = False
before the inner loop, and if doublebreak: break
after the inner loop, then do doublebreak = True; break
inside the inner loop.
Google for some bytecode hacks that add a way to do multi-level breaks (with some slightly ugly syntax) to the language, and build an import hook around them. (Or maybe use MacroPy instead.)
Google for the even uglier hacks that add goto
support to Python; you can easily simulate labeled breaks with goto
, and labeled breaks are usually a good substitute for multi-level breaks.