Kodokon kodokon.com

Loops: for, while, break, and continue

You repeat instructions with for and while, and control your loops with range, break, and continue.

8 min · 3 questions

Open this lesson in Kodokon

A loop repeats a block of instructions several times, without you having to copy it out again. The for loop repeats a number of times known in advance. It's often used with range, a function that produces a sequence of numbers: range(5) gives 0, 1, 2, 3, 4 (you start from 0 and the end bound is excluded). As with if, the line ends with : and the repeated block is indented by 4 spaces.

PYTHON
for number in range(5):
    print(number)
Displays the numbers from 0 to 4, one per line.

range also accepts a start: range(1, 6) gives 1, 2, 3, 4, 5. The while loop repeats its block as long as a condition is true. You use it when you don't know in advance how many rounds there will be. Careful: the block must make the condition evolve, otherwise the loop never stops.

PYTHON
countdown = 3
while countdown > 0:
    print(countdown)
    countdown = countdown - 1
print("Go!")
Displays 3, 2, 1, then "Go!": countdown decreases with each round.

Two keywords let you control a loop from the inside: break exits immediately from the loop, and continue skips to the next round without running the rest of the block. In the example below, % gives the remainder of a division: number % 2 == 0 therefore tests whether a number is even.

PYTHON
for number in range(10):
    if number == 5:
        break
    if number % 2 == 0:
        continue
    print(number)
Displays 1 then 3: even numbers are skipped, and the loop stops at 5.

Knowledge check

Make sure you remember the key points of this lesson.

  1. How many times does the block of for i in range(3): run?
    • 2 times
    • 3 times
    • 4 times
  2. What does the break keyword do in a loop?
    • It pauses the loop
    • It exits the loop immediately
    • It restarts the loop from the beginning
    • It moves to the next round
  3. What happens if a while condition stays true forever?
    • The loop never stops
    • Python fixes the program automatically
    • The loop runs only once