break statement
The Python break statement, just like in the C language, breaks the smallest closed for or while loop.
The break statement is used to terminate the loop statement, that is, if the loop condition does not have a False condition or the sequence has not been completely recursed, it will stop executing the loop statement.
The break statement is used in while and for loops.
If you use nested loops, the break statement will stop executing the deepest loop and start executing the next line of code.
continue statement
The Python continue statement jumps out of this loop, and break jumps out of the entire loop.
The continue statement is used to tell Python to skip the remaining statements in the current loop, and then continue to the next loop.
The continue statement is used in while and for loops.
Example extension:
How to exit multi-layer loop in python
1、 Define the tag variable; use the change of the variable value to exit the loop
# The first form of nesting
a =[[1,2,3],[5,5,6],[7,8,9]]
# init_i =0
# init_j =0
flag = True
for i inrange(3):for j inrange(3):
# print(i, j)if a[i][j]==5:
flag = False
init_i = i
init_j = j
breakif not flag:breakprint(init_i, init_j)print(i, j)
# The second form of nesting
flag = True
while flag:for i inrange(10):print(x)
flag = False
break
2、 Use the function with the return keyword to break out of the loop (as long as the return statement is executed inside the function, the function will exit directly)
def test():while True:for x inrange(10):print(x)returntest()
3、 Use else continue and outer break to break out of the loop
a =[[1,2,3],[5,5,6],[7,8,9]]
init_i =0
init_j =0
flag = True
for i inrange(3):for j inrange(3):
# print(i, j)if a[i][j]==5:
flag = False
init_i = i
init_j = j
breakelse:continuebreak
# if not flag:
# breakprint(init_i, init_j)print(i, j)
while True:for x inrange(4):print(x)if x ==2:breakelse:print("Not performed")continuebreak
So far, this article on how to exit the loop in python is introduced. For more related content on how to exit the loop in python, please search the previous articles of ZaLou.Cn or continue to browse the related articles below. Hope you will support ZaLou.Cn more in the future!
Recommended Posts