Python exit loop

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

Python exit loop
Detailed Python loop nesting
05. Python entry value loop statement
Python multithreading
Python CookBook
Python FAQ
Python3 dictionary
Python3 module
python (you-get)
Python string
Python basics
Python descriptor
Python basics 2
Python exec
Python notes
Python3 tuple
CentOS + Python3.6+
Python advanced (1)
Python decorator
Python IO
Python multithreading
Python toolchain
Python3 list
Python multitasking-coroutine
Python overview
python introduction
Python analytic
Python basics
07. Python3 functions
Python basics 3
Python multitasking-threads
Python functions
python sys.stdout
python operator
Python entry-3
Centos 7.5 python3.6
Python string
python queue Queue
Python basics 4
Python basics 5