LightMySky

Count-Controlled Loops

Repeating a block a known number of times, with a loop variable that takes each value of a range in turn.

No account needed. Progress saves in this browser.

What a learner can do afterwards

  • Write a loop that repeats a fixed number of times
  • Use the loop variable inside the body, for example to print a times table
  • Say how many times a loop over a given range will run, before running it

1 · Read

A for loop repeats its block once for every item in a group, like the numbers from range(). Each pass hands the loop variable the next number, and the body runs once for it. Since you know the group up front, you know the repeat count before the loop starts.

Try it together

Printing the 9 times table needs 13 lines without a loop, one per multiple from 0 to 12. A loop does it in two lines: for each i in range(13), print 9 times i. Your 7 times table works the same way with range(13).

range() takes a start, a stop and a step, where the start counts but the stop never prints. So range(10, 26, 5) gives 10, 15, 20 and 25, which is 4 passes. Use the loop variable inside the body, and the loop ends exactly when the count says it will.

Good to know

Say the repeat count aloud before you run anything. If the loop counts down, check that each step moves toward the stop, or it will never finish.

A count-controlled loop runs once per value in its range, and you can count the passes in advance.

2 · Watch

Take it off screen

Print a worksheetA4 with an answer key page for grown-ups. No screen, no internet.

Where it sits

Then practise

8 questions wait behind this lesson, each with its answer explained. Every answer feeds the sky: stars light as they are learned, and dim when it is time to come back.

Spotted a problem on this page? Tell us
Count-Controlled Loops · Computing, ages 14 to 16 · LightMySky