Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to break out of nested loops in python?

Tags:

python

what is the difference between these sets of loops?

for i in range(0,5):
    print i,'i'
    for x in range(0,4):
        print x,'x'
    break

AND

for i in range(0,5):
    print i,'i'
    for x in range(0,4):
        print x,'x'
        break

what's the scope of break statement?

like image 461
Anonamous Avatar asked Nov 27 '22 05:11

Anonamous


1 Answers

A break will only break out of the inner-most loop it's inside of. Your first example breaks from the outer loop, the second example only breaks out of the inner loop.

To break out of multiple loops you need use a variable to keep track of whether you're trying to exit and check it each time the parent loop occurs.

is_looping = True
for i in range(5): # outer loop
    for x in range(4): # inner loop
        if x == 2:
            is_looping = False
            break # break out of the inner loop

    if not is_looping:
        break # break out of outer loop
like image 97
Soviut Avatar answered Dec 06 '22 23:12

Soviut