Python break Statement

The Python break statement, like in C language, breaks out of the smallest enclosing for or while loop.

The break statement is used to terminate a loop statement, that is, even if the loop condition is not False or the sequence has not been fully iterated through, the loop statement will still stop executing.

The break statement is used in while and for loops.

If you use nested loops, the break statement will stop executing the innermost loop and start executing the next line of code.

Python language break statement syntax:

break

Flowchart:

Examples (Python 2.0+)

#!/usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': # First example if letter == 'h': break print 'Current letter :', letter var = 10 # Second example while var > 0: print 'Current variable value :', var var = var -1 if var == 5: # Exit the loop when variable var equals 5 break print "Good bye!"

The execution result of the above examples:

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