Python Foundations · Lesson 6 of 12

Count-controlled loops

for loops and range(). Learn through short examples, practical tasks and targeted questions.

← All lessons

Repeating with for and range

A count-controlled loop is useful when you know how many repetitions are needed. range() creates a sequence of integers; its stop value is not included. Trace the loop variable for each iteration and predict exactly how many outputs appear.

Watch out: range(5) produces 0, 1, 2, 3, 4—not 1 through 5. This is a common off-by-one error.

1 · Understand

for loops and range(). Study the code and predict what it does before running it. Change a value or string and observe how the output changes.

for number in range(1, 6):
    print(number)
Download example .py ↓

2 · Practise

Print the seven-times table from 7 × 1 to 7 × 12.

Plan your inputs, processing and outputs. Write the code in Mu, IDLE or PyCharm; test at least three cases.

Show a reference solution after attempting the task
for n in range(1, 13):
    print("7 x", n, "=", 7 * n)
Download reference solution .py ↓

3 · Debug the code

Identify the problem and explain how to fix it before revealing the answer.

for x in range(5)
    print(x)
Reveal the corrected program and explanation
for x in range(5):
    print(x)

Compare the two snippets. Identify the changed line, run the corrected version and explain the effect.

4 · Check your understanding

How many times does for n in range(4) run?

5 · Challenge and reflect

Extension: Improve your solution to deal with unexpected input, add a second feature or display results more clearly.

Reflect: What was the hardest part? What would you test if someone else used your program?

Want extra practice? Try interactive Python tracing and debugging questions →