Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break nested for loop in Python?

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.

like image 554
user3616181 Avatar asked Sep 09 '14 10:09

user3616181


2 Answers

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
like image 64
perreal Avatar answered Oct 30 '22 12:10

perreal


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
like image 29
semptic Avatar answered Oct 30 '22 12:10

semptic