Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python break statement


May 10, 2021 Python2


Table of contents


Python break statement

Python break statements, like in C language, break the minimum closed for or while loop.

The break statement is used to terminate the loop statement, i.e. the loop condition does not have a False condition or the sequence is not fully recursive, and the loop statement is stopped.

Break statements are used in while and for loops.

If you use nested loops, the break statement stops executing the deepest loop and starts executing the next line of code.

Python language break statement syntax:

break

Flow chart:

Python break statement

Instance:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
for letter in 'Python':     # 第一个实例
   if letter == 'h':
      break
   print '当期字母 :', letter
  
var = 10                    # 第二个实例
while var > 0:              
   print '当期变量值 :', var
   var = var -1
   if var == 5:   # 当变量 var 等于 5 时退出循环
      break
 
print "Good bye!"

The results of the above example execution:

当期字母 : P
当期字母 : y
当期字母 : t
当期变量值 : 10
当期变量值 : 9
当期变量值 : 8
当期变量值 : 7
当期变量值 : 6
Good bye!