break
statementWhen a break
statement executes inside a loop, control flow “breaks” out of the loop immediately:
i = 0
while i < 7:
print(i)
if i == 4:
print("Breaking from loop")
break
i += 1
The loop conditional will not be evaluated after the break
statement is executed. Note that break
statements are only allowed inside loops, syntactically. A break
statement inside a function cannot be used to terminate loops that called that function.
Executing the following prints every digit until number 4
when the break
statement is met and the loop stops:
0
1
2
3
4
Breaking from loop
break
statements can also be used inside for
loops, the other looping construct provided by Python:
for i in (0, 1, 2, 3, 4):
print(i)
if i == 2:
break
Executing this loop now prints:
0
1
2
Note that 3 and 4 are not printed since the loop has ended.
If a loop has an else
clause, it does not execute when the loop is terminated through a break
statement.
continue
statementA continue
statement will skip to the next iteration of the loop bypassing the rest of the current block but continuing the loop. As with break
, continue
can only appear inside loops:
for i in (0, 1, 2, 3, 4, 5):
if i == 2 or i == 4:
continue
print(i)
0
1
3
5
Note that 2
and 4
aren’t printed, this is because continue
goes to the next iteration instead of continuing on to print(i)
when i == 2
or i == 4
.
break
and continue
only operate on a single level of loop. The following example will only break out of the inner for
loop, not the outer while
loop:
while True:
for i in range(1,5):
if i == 2:
break # Will only break out of the inner loop!
Python doesn’t have the ability to break out of multiple levels of loop at once – if this behavior is desired, refactoring one or more loops into a function and replacing break
with return
may be the way to go.