ScanSkill

break

This break statement is used to terminate the execution of a loop.

Syntax

loop:
    break
else:
    statement(s)

Here,

  • loop: Either of for or while loop.
  • statement(s): Block of code to be executed.
  • else: Optional. Used to indicate the block of code to be executed when loop terminates without break statement.

Note: break terminates the nearest enclosing loop, skipping the optional else clause if the loop has one. If a for loop is terminated by break, the loop control target keeps its current value.

When break passes control out of a try statement with a finally clause, that finally clause is executed before really leaving the loop.

A break statement executed in the first statement(s) terminates the loop without executing the else clause’s statement(s).

Examples

  • With for loop
>>> for i in range(5):
...     if i == 3:
...         break
...     print i
...
0
1
2
  • With while loop
>>> i = 0
>>> while i < 10:
...     try:
...        if i == 5:
...             break
...        print i
...        i += 1
...     finally:
...        print 'this is executed, i = ', i
...
0
this is executed, i =  1
1
this is executed, i =  2
2
this is executed, i =  3
3
this is executed, i =  4
4
this is executed, i =  5
this is executed, i =  5