Help breaking out of nested loops

re the following simplified code fragment:

for i in range(nnn):
    for j in range(nnn):
        if (function1 call returns True):
            if (function 2 call returns True):                    
                result = (some result)
                break

I want to break out of the whole block once both fn1 and fn2 return True. “break” only takes me out of its loop, after which the i-loop still runs.

This is not a showstopper since I can rewrite the block with while loops and incremented counters, but it ends up with several more lines.

I’m looking for a way to control the number of levels you go back up. Thanks in advance for your advice.

Re indents: spaces and option-spaces get lost. thanks for the back-tick tip…

1 Like

When dealing with similar situations, I put the block in a separate function, and use return result instead of break. The overhead of a single function call is negligible and readability is usually greatly improved.

2 Likes

That works, with a nice speed increase as well.

1 Like

This is great advice, and I’d like to specifically emphasize the readability factor. When your code becomes nested to the degree of the above, it’s a very strong indication that it should be refactored into separate functions/methods.

That’s a significant part of why Python does not define a keyword or some form of “labeled loops” to break or continue to a specific level. Typically, it’s only a real issue in overly nested code that ought to be refactored anyways.

1 Like