Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

break two for loops [duplicate]

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!
like image 449
MBZ Avatar asked Jan 27 '12 18:01

MBZ


People also ask

Does Break break out of both 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.

Can you break for loops?

Breaking Out of For Loops. To break out of a for loop, you can use the endloop, continue, resume, or return statement.

How do you break out of all loops?

Put the loop in a function and use return to break out of all the loops at once.


1 Answers

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
like image 161
phihag Avatar answered Oct 23 '22 23:10

phihag