Python Controlling Loops with break and continue
In Python,break and continue are two keywords used to control loop flow.break is used to terminate the entire loop immediately, while continue is used to skip the current iteration and go straight to the next one.
Below is sample code showing how to use break and continue to control loops.
Example
Example Code
for
i
in
range
(
1
,
11
)
:
if
i
==
5
:
continue
Skip the current iteration
if
i
==
8
:
break
Terminate the loop
(
i
)
Code analysis:
for i in range(1, 11):: This is afora for loop, theiStarts from 1 and ends at 10.if i == 5:: WheniWhen it equals 5, thecontinuestatement is executed, skipping the current iteration and going straight to the next one. Therefore the number 5 is not printed.if i == 8:: WheniWhen it equals 8, thebreakstatement is executed, terminating the entire loop immediately. Therefore the number 8 and all following numbers are not printed.print(i): print the currentivalues.
Output result:
1
2
3
4
6
7
In this example the number 5 is skipped, and the number 8 and those after it are not printed because of the break statement.
Python3 Examples