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

Python Controlling Loops with break and continue

Python Controlling Loops with break and continue

Document Object Reference Manual Python3 Examples

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

   

print

(

i

)

Code analysis:

  1. for i in range(1, 11):: This is a for a for loop, thei Starts from 1 and ends at 10.
  2. if i == 5:: When i When it equals 5, the continue statement is executed, skipping the current iteration and going straight to the next one. Therefore the number 5 is not printed.
  3. if i == 8:: When i When it equals 8, the break statement is executed, terminating the entire loop immediately. Therefore the number 8 and all following numbers are not printed.
  4. print(i): print the current i values.

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.

Document Object Reference Manual Python3 Examples