PySchools Python Quick Reference Guide

Repetitions with while loops

«  Repetitions with for loops   ::   Contents   ::   Lists  »

Repetitions with while loops

In programming, while loop is usually used to perform some repetitive tasks that may be executed one or more times based on some condition. The code below shows a sample while loop in Python:

i = 0               # usually has a control variable to start the while loop
while i < 10:       # terminating condition: while loop will terminate if i >= 10
    i += 2          # changing the value of the control variable
    print i

#output:
2
4
6
8
10

Early termination using break

You can use the break statement to cause early termination. The break statement causes the execution to immediately exit the while block and continue with the next statement after the while block, if any.

i = 0
while i < 10:
    i += 2
    if i>5:
       break       # exit 'while' loop if i is greater than 5
    print i

#output:
2
4

Skip iteration with continue

You can use the continue statement to skip certain iteration. The continue statement causes the execution to skip the rest of the statements within the while block for that iteration.

i = 0
while i < 10:
    i += 2
    if i==4:
       continue   # next 'print' statement is skipped when i equals 4.
    print i

#output:
2
6
8
10

See also

Ready for some practice? Test your understanding at PySchools: While Loops.

«  Repetitions with for loops   ::   Contents   ::   Lists  »