Break out of nested loops with max. 4 lines of code, no matter how deeply they are nested
PythonMIT
Break out of nested loops with max. 4 lines of code, no matter how deeply they are nested
The problem: breaking out of nested loops
pip install break-out-nested
# Break out of nested loops - a pain in the ***# How it is usually done:done=Falseforiinrange(1, 6, 1): # 1st loopprint('i:', i)
forjinrange(1, 11, 2): # 2nd loopprint(' i, j:', i, j)
forkinrange(1, 21, 4): # 3rd loopprint(' i,j,k:', i, j, k)
ifi%3==0andj%3==0andk%3==0:
done=Truebreak# breaking from 3rd loopifdone: break# breaking from 2nd loopifdone: break# breaking from 1st loop
The solution
# Way easierfrombreak_out_nestedimportit, bol# you need to create new variables as attributes of it,# because break_out_nested has only access to these variablesit.i, it.j, it.k=1, 1, 1# the break conditiondefcond(): returnit.i%3==0andit.j%3==0andit.k%3==0# The condition will be checked in each loop# The function that checks the condition has to be passed as the last argument. # You can pass as many iterables as you want to the functionforit.i, it.j, it.kinbol(range(1, 6, 1), range(1, 11, 2), range(1, 21, 4), cond):
print(it.i, it.j, it.k)
More examples
# More examplesdefcond(): returnit.i+it.j+it.k==777it.i, it.j, it.k=0, 0, 0forit.i, it.j, it.kinbol(range(100), range(1000), range(10000), cond):
print(it.i, it.j, it.k)
defcond(): returnit.i+it.j+it.k>=100000it.i, it.j, it.k=0, 0, 0# you don't have to use it.i, it.j, it.k as the loop variables, you can# use anything you want, but you have to update the variables somewherefori, j, kinbol(range(100), range(1000), range(10000), cond):
it.i, it.j, it.k=i*10, j*100, k*100print(it.i, it.j, it.k)