The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Popsicle Puzzles

--

Chapters
00:00 Several Nested 'For' Loops, Continue To Next Iteration Of Outer Loop If Condition Inside Inn
00:24 Accepted Answer Score 4
00:38 Answer 2 Score 0
00:51 Answer 3 Score 2
01:12 Answer 4 Score 0
01:25 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