Breaking out of nested loops
for x in xrange(10):
for y in xrange(10):
print x*y
if x*y > 50:
break
else:
continue # only executed if the inner loop did NOT break
break # only executed if the inner loop DID break
The same works for deeper loops:
for x in xrange(10):
for y in xrange(10):
for z in xrange(10):
print x,y,z
if x*y*z == 30:
break
else:
continue
break
else:
continue
break
It has at least been suggested, but also rejected. I don't think there is another way, short of repeating the test or re-organizing the code. It is sometimes a bit annoying.
In the rejection message, Mr van Rossum mentions using return
, which is really sensible and something I need to remember personally. :)
If you're able to extract the loop code into a function, a return
statement can be used to exit the outermost loop at any time.
def foo():
for x in range(10):
for y in range(10):
print(x*y)
if x*y > 50:
return
foo()
If it's hard to extract that function you could use an inner function, as @bjd2385 suggests, e.g.
def your_outer_func():
...
def inner_func():
for x in range(10):
for y in range(10):
print(x*y)
if x*y > 50:
return
inner_func()
...