Possible Duplicate:
How to break out of multiple loops in Python?
is it possible to break out of two for loops in Python?
i.e.
for i in range(1,100):
for j in range(1,100):
break ALL the loops!
Possible Duplicate:
How to break out of multiple loops in Python?
is it possible to break out of two for loops in Python?
i.e.
for i in range(1,100):
for j in range(1,100):
break ALL the loops!
No, there is no nested break
statement in python.
Instead, you can simplify your function, like this:
import itertools
for i,j in itertools.product(range(1, 100), repeat=2):
break
.. or put the code into its own function, and use return
:
def _helper():
for i in range(1,100):
for j in range(1,100):
return
_helper()
.. or use an exception:
class BreakAllTheLoops(BaseException): pass
try:
for i in range(1,100):
for j in range(1,100):
raise BreakAllTheLoops()
except BreakAllTheLoops:
pass
.. or use for-else-continue:
for i in range(1,100):
for j in range(1,100):
break
else:
continue
break
.. or use a flag variable:
exitFlag = False
for i in range(1,100):
for j in range(1,100):
exitFlag = True
break
if exitFlag:
break
Several solutions were proposed in PEP 3136, but the BDFL rejected it:
I'm rejecting it on the basis that code so complicated to require this feature is very rare. In most cases there are existing work-arounds that produce clean code, for example using 'return'. While I'm sure there are some (rare) real cases where clarity of the code would suffer from a refactoring that makes it possible to use return, this is offset by two issues:
The complexity added to the language, permanently. This affects not only all Python implementations, but also every source analysis tool, plus of course all documentation for the language.
My expectation that the feature will be abused more than it will be used right, leading to a net decrease in code clarity (measured across all Python code written henceforth). Lazy programmers are everywhere, and before you know it you have an incredible mess on your hands of unintelligible code.
No you cannot specify how many loops to break. Put your code in a function and use return
.
Another option: use a flag variable in the inner loop and set it to True
when you use break
. Then use it for break
ing the outer loop.
for i in range(1,100):
breaking = false
for j in range(1,100):
if foundAReasonToBreak:
breaking = true
break
if breaking:
break
try:
for i in range(1,10):
print i
for j in range(1,10):
if j == 5: raise AssertionError
print j
except AssertionError:
pass
print "I'm free"
This is a little distasteful but it does seem to accomplish what you're asking.
Edit: I see @phihag posted something similar as I was experimenting.