Search code examples
pythonpython-3.xnested-loopsbreakcontinue

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


I know it is terribly inefficient and ugly code, but if I have three for loops, nested inside each other such as so:

for x in range(0, 10):
    for y in range(x+1, 11):
       for z in range(y+1, 11):
           if ...

I want to break the two inner loops and continue to the next iteration of the outer loop if the if statement is true. Can this be done?


Solution

  • 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;
            #...