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 |
def
work():
#定义函数
for i
in
range
(
5
):
print
(
"i="
, i)
for
j
in
range
(
5
):
print
(
"--j="
, j)
for
k
in
range
(
5
):
if
k<
2
:
print
(
"------>k="
, k)
else
:
return
i,j,k
print
(work())
|
Method Two:
Define variables, change the state of variables, do not meet the conditions, loop out
123456789101112131415 |
break_flag
=
False
for
i
in
range
(
10
):
print
(
"爷爷层"
)
for
j
in range
(
10
):
print
(
"爸爸层"
)
for
k
in
range
(
10
):
print
(
"孙子层"
)
if
k
=
=
3
:
break_flag
=
True
break
#跳出孙子层循环,继续向下运行
if
break_flag
=
=
True
:
break
#满足条件,运行break跳出爸爸层循环,向下运行
if
break_flag
=
=
True
:
break #满足条件,运行break跳出爷爷层循环,结束全部循环,向下运行
print
(
"keep going..."
)
|
Method Three:
While loop statement, define condition, condition change, Loop end
123456789101112131415 |
break_flag
=
False
count
=
0
while
break_flag
=
=
False
:
print
(
"爷爷层..."
)
while
break_flag
=
=
False
:
print
(
"爸爸层..."
)
while
break_flag
=
=
False
:
if
count<
5
:
print
(
"孙子层..."
)
count
+
=
1
else
:
break_flag
=
True
print
(
"keep going..."
)
|
Python (3)-loop statement: Jump out of a multilayer loop from the inner layer