Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python break Statement

Python break Statement

The Python break statement, as in the 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, 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 stops the execution of the innermost loop and begins executing the next line of code.

Syntax of the break statement in the Python language:


break

Flow diagram:

Example (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 the variable var equals 5

break

print

"

Good bye!

"

The example above produces:


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