The Python Oracle

Several nested 'for' loops, continue to next iteration of outer loop if condition inside inner loop is true

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping

--

Chapters
00:00 Question
00:38 Accepted answer (Score 4)
00:55 Answer 2 (Score 2)
01:21 Answer 3 (Score 0)
02:11 Answer 4 (Score 0)
02:30 Thank you

--

Full question
https://stackoverflow.com/questions/3472...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #nestedloops #break #continue

#avk47



ACCEPTED ANSWER

Score 4


Check some variable after each loops ends:

for x in range(0, 10):
    for y in range(x+1, 11):
        for z in range(y+1, 11):
            if condition:
                variable = True
                break
            #...
        if variable:
            break;
        #...



ANSWER 2

Score 2


Another option is to use exceptions instead of state variables:

class BreakException(Exception):
    pass

for x in range(0, 10):
    try:
        for y in range(x+1, 11):
           for z in range(y+1, 11):
               if True:
                   raise BreakException
    except BreakException:
        pass

I imagine this could be especially useful if bailing out of more than two inner loops.




ANSWER 3

Score 0


n = False
for x in range(0,10):
    if n == True:
        print(x,y,z)
    for y in range(x+1, 11):
        if n == True:
            break
        for z in range(y+1, 11):
            if z == 5:
                n = True
                break

(1, 2, 5)
(2, 2, 5)
(3, 3, 5)
(4, 4, 5)
(5, 5, 5)
(6, 6, 5)
(7, 7, 5)
(8, 8, 5)
(9, 9, 5)



ANSWER 4

Score 0


A possible solution is to merge the two inner loops to a single one (that can be terminated with break):

import itertools

for x in range(10):
    for y, z in itertools.combinations(range(x+1, 11), 2):
        if condition:
            break