Python Forum

Full Version: best way out of nested loops?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
the best and most Pythonic way (in your opinion) to get all the way out of a few nested loops is?
Break statement I guess? Or if you're looking for something more drastic, sys.exit?
maybe look for way to refactor code without nested loops (can you use itertools.product and break?)?
maybe separate loops in function and return?
(May-27-2020, 07:21 AM)Knight18 Wrote: [ -> ]Break statement I guess?
just break will break out of the one specific loop, but the question is about nested loops and break out all the way
My kludge would be to set a flag in that innermost loop, and then test for the flag when coming out (and break again). This works:
for loop1 in range(10):
    for loop2 in range(10):
        for loop3 in range(10):
            for loop4 in range(10):
                x = input('break')
                flag = True
                break
            if flag:
                break
            #do other stuff
        if flag:
            break
        #do other stuff
    if flag:
        break
    #do more other stuff
@jefsummers your solution is a candidate for refactoring.

def loop():
    for i in range(10):
        for j in range(10):
            if i*j > 10:
                return i, j
Just put everything in a function, return if the condition is fulfilled.
If tasks afterwards are necessary, you could work with the return value of the loop function.
I would try to flatten the logic if I could. Failing that I would try to "return" out. Failing that I would raise an exception.
i like the function idea. but that has the context problem where you might need to pass lots of data. that is where refactoring is needed. i think raising an exception is a kludge. exceptions have a purpose and this is not it. still, it can be a quick way to get at this kind of issue when the cost (such as time) of refactoring is too high.