Jump out of the multilayer loop: three-layer loop, the innermost layer directly jumps out 3 layers
Method One:
In Python, the function runs to return and stops, so you can use this feature to write functions as functions to terminate multiple loops
| 1234567891011121314 |
defwork(): #定义函数 for i inrange(5): print("i=", i) forj inrange(5): print("--j=", j) fork inrange(5): ifk<2: print("------>k=", k) else: returni,j,k print(work()) |
Method Two:
Define variables, change the state of variables, do not meet the conditions, loop out
| 123456789101112131415 |
break_flag=Falsefori inrange(10): print("爷爷层") forj in range(10): print("爸爸层") fork inrange(10): print("孙子层") ifk==3: break_flag=True break#跳出孙子层循环,继续向下运行 ifbreak_flag==True: break#满足条件,运行break跳出爸爸层循环,向下运行 ifbreak_flag==True: break #满足条件,运行break跳出爷爷层循环,结束全部循环,向下运行print("keep going...") |
Method Three:
While loop statement, define condition, condition change, Loop end
| 123456789101112131415 |
break_flag=Falsecount=0whilebreak_flag==False: print("爷爷层...") whilebreak_flag==False: print("爸爸层...") whilebreak_flag==False: ifcount<5: print("孙子层...") count+=1 else: break_flag=Trueprint("keep going...") |
Python (3)-loop statement: Jump out of a multilayer loop from the inner layer