Skip to content
Topic 5 of 6

Loops

Repeat work with for and while, count with range(), and steer loops with break and continue.

25 min read 5 pages 5 practice games Jump to practice ↓

Page 1

for loops

A for loop repeats a block once for each item in a sequence or other collection, such as a list, a string, a range, a tuple, a dictionary or a set. The loop variable takes each item in turn.

python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)
# apple
# banana
# cherry

Looping over a string gives one character at a time:

python
for ch in "hi":
    print(ch)   # h, then i

A for loop stops by itself when it runs out of items. Each pass through the loop body is called an iteration.

Page 2

range(start, stop, step)

The built-in range() makes a sequence of whole numbers, which is perfect for counting loops.

  • range(stop) counts from 0 up to, but not including, stop: range(5) gives 0, 1, 2, 3, 4.
  • range(start, stop) starts at start: range(2, 6) gives 2, 3, 4, 5.
  • range(start, stop, step) moves by step each time: range(0, 10, 3) gives 0, 3, 6, 9.
  • A negative step counts down: range(5, 0, -1) gives 5, 4, 3, 2, 1.

The stop value is never included. range(5) has 5 numbers, but the last one is 4. The step can't be 0: range(1, 5, 0) raises a ValueError.

python
total = 0
for n in range(1, 4):
    total += n
print(total)   # 6 (1 + 2 + 3)

Page 3

while loops

A while loop repeats its block as long as its condition is true. Python checks the condition before every iteration, so if it is false at the start, the body never runs.

python
count = 3
while count > 0:
    print(count)
    count -= 1
print("Liftoff!")
# 3, 2, 1, Liftoff!

Use while when you don't know in advance how many times to loop, such as asking for input until it is valid. Use for when you're stepping through a sequence or a known range.

If nothing in the body ever makes the condition false, you get an infinite loop: the program runs forever. Press Ctrl+C to stop it.

Page 4

break, continue and else

  • break exits the loop immediately; the code after the loop runs next.
  • continue skips the rest of the current iteration and jumps to the next one.
python
for n in range(10):
    if n == 5:
        break
    if n % 2 == 0:
        continue
    print(n)   # 1, then 3

Loops can have an else block too. It runs when the loop finishes normally, and it is skipped if the loop ends with break. It is handy for searches:

python
for n in [3, 7, 9]:
    if n % 2 == 0:
        print("found an even number")
        break
else:
    print("no even numbers")   # runs: no break happened

Page 5

Off-by-one errors

An off-by-one error is a loop that runs one time too many or one time too few. The most common cause is forgetting that range() stops before its stop value. To count from 1 to 10 inclusive, write range(1, 11), not range(1, 10).

Another cause is a while condition that uses < where you needed <=, or the other way round. Before you run a loop, check its first and last values by hand.

Finished reading?

Mark it as read for +20 XP. Optional: practice is open either way.

Practice

Pass any one game to unlock Topic 6: Functions.

Sign in to play, save your best and unlock Topics.
  • Reach −1,500 m
  • Reach 150 km
  • 7/10 without falling
  • Clear both boards
  • 150 points

Learn more