Python Forum

Full Version: breaking outof nexted loops
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
one of the many coding difficulties i encounter in most languages is breaking out of 2 or more nested loops. in C i did have a goto but that was considered bad code. i do recall there was a language that allowed break to have a number (always must be a hard coded literal constant) to specify the number of loop levels to break out of. the usual way is to break out of each level one at a time based on a specific variable or specific value(s). constrained types like bytearray can sometimes force an extra variable.

what coding techniques to do things like this have you come up with?
Can you refactor your code to use single loop to iterate over itertools.product instead of having nested loops?
Suggested practice is the use of 'return': Guido rejecting PEP 3136 -- Labeled break and continue.

Of course one can break out of nested loop but this is not something which is easy to understand - using for-loop with else and then break:

for loop:                 # outer loop
    # do something
    for loop:             # inner loop
        # do something
        # outcome: break or no-break
    else:                 # no-break
        continue          # go back to outer loop
    break                 # break occured in inner loop, break outer loop as well
 
Skaperen Wrote:what coding techniques to do things like this have you come up with?
A simple way to exit a deeply nested loop in python is to raise an exception. In fact I once wrote a thread in this forum with a 'context' specially designed to exit deeply nested loops, even across functions boundaries. It remains a case study, because I don't use it in practice.
i could use return if the context change could be dealt with. i do like the idea of exceptions but i think refactoring to use itertools.product would be best for cases where that can be done.