5

I wonder how to get out from loop like this:

for a in range(95):
    for b in range(95):
        for c in range(95):
            for d in range(95):
                ...
                do some computings
                ...
                if condition:
                    task completed

After task is completed all loops and computings are continued. They have to be broke but I don't know how - single break statement after "task completed" will end only innermost for loop but it will be invoked again multiple times - so we gain nothing.

In C I would do a=b=c=d=95 but in python that wouldn't work. Of course I can use while loop instead but then I have to use X+=1 statements and it would look awful.

Any help?


About the loop: I use it to break a 4-char password using brute-force. It isn't a real purpose - used only for tests.

user3616181
  • 975
  • 2
  • 8
  • 27
  • 13
    Separate it into a method and then return from the method – Sayse Sep 09 '14 at 10:17
  • 1
    Or you could wrap the whole thing inside a `try ... except` block and `raise` an exception to break out of the innermost loop. However, Sayse's solution is cleaner. – Roberto Reale Sep 09 '14 at 10:22

2 Answers2

12

Using itertools product:

from itertools import product
for a, b, c, d in product(range(95), range(95), range(95), range(95)):
    print a, b, c, d
    if a == 1: break

Shorter version, thanks Ashwini:

for a, b, c, d in product(range(95), repeat=4):
    print a, b, c, d
    if a == 1: break
perreal
  • 94,503
  • 21
  • 155
  • 181
4

You can use a exception to break out of nested loops:

class Break(Exception): pass

try:
    for a in range(95):
        for b in range(95):
            for c in range(95):
                for d in range(95):
                    # ...
                    # do some computings
                    # ...
                    if condition:
                        # task completed
                        raise Break()
except Break:
    # do some stuff

or with StopIteration:

try:
    for a in range(95):
        for b in range(95):
            for c in range(95):
                for d in range(95):
                    # ...
                    # do some computings
                    # ...
                    if condition:
                        # task completed
                        raise StopIteration()
except StopIteration:
    # do some stuff
semptic
  • 645
  • 4
  • 15