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!
Using break in a nested loopIn a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.
Put the loop in a function and use return to break out of all the loops at once.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With