This break
statement is used to terminate the execution of a loop.
loop:
break
else:
statement(s)
Here,
for
or while
loop.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).
for
loop>>> for i in range(5):
... if i == 3:
... break
... print i
...
0
1
2
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