Count-controlled loops: for

range, the loop variable, and repeating a known number of times.

F2.5Decisions and loopsGCSE15 min

Covers OCR J277 2.2.1 Programming fundamentals · AQA 8525 3.2.2 Programming concepts · Edexcel 1CP2 6.2.2 Sequence, selection, repetition and iteration

Do this lesson in the simulator

To drive a square you could write forward, turn, forward, turn, forward, turn, forward, turn. Eight lines for one idea repeated four times. A loop writes the idea once and says how many times. Repeating code is called iteration, and a loop that runs a set number of times is count-controlled.

for and range

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for i in range(4):
    print("side", i)
    forward(60, distance=25)
    turn_right(30, angle=90)

Run this in the simulator

Three things in the first line. range(4) produces four numbers: 0, 1, 2, 3. for i in takes them one at a time and puts each into the loop variable i. The indented block runs once for each. Four sides, four turns, a square.

The square the first program drives, seen from above: four sides labelled i = 0, 1, 2 and 3, each followed by a right turn of 90 degrees, ending back at the start facing the way it begani = 0forward 25 cmi = 1forward 25 cmi = 2forward 25 cmi = 3forward 25 cmstart and finishat every corner:turn_right, 90 degrees
One block, four times round. The block is the same every time; only i changes, from 0 to 3, and after four right turns the robot faces the way it started.

The block under a for is just like the block under an if: colon, indent, same rules.

Counting from zero

Programmers count from zero, so range(4) is 0, 1, 2, 3 and never 4. If you want to print 1 to 4 for a human, add one, or start the range at 1:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for i in range(4):
    print("corner number", i + 1)

for n in range(1, 5):
    print("also", n)

for n in range(0, 20, 5):
    print("in fives", n)

Run this in the simulator

range(1, 5) gives 1, 2, 3, 4: it starts at the first number and stops before the second. A third number is the step: range(0, 20, 5) counts 0, 5, 10, 15.

Number lines from 0 to 20 for range(4), range(1, 5) and range(0, 20, 5): filled dots at the numbers each one gives, and an open dot at the stop number, which is never givenrange(4)0, 1, 2, 3+1stop: 4 is not givenrange(1, 5)1, 2, 3, 4+1stop: 5 is not givenrange(0, 20, 5)0, 5, 10, 15+5stop: 20 is not given05101520
range() starts at the first number and hops by the step, but it stops before the stop number: the open dot is never given. That is why range(4) gives four numbers and none of them is 4.

The loop variable is useful

i changes every time round. Use it. Turn your sound on for this one:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for step in range(8):
    note = 300 + step * 50
    print("step", step, "note", note)
    tone(note, 0.2)

Run this in the simulator

Each time round, the note is worked out from step, so the piezo climbs. Change 50 to 100, or 8 to 12.

Predict, then run

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

total = 0
for i in range(5):
    total = total + i
    print("i is", i, "total is", total)
print("final total", total)

Run this in the simulator

Work through it by hand first: what is total after each time round? Writing the values down in a table, one row per time round, is exactly what an exam trace table is.

Loops and decisions together

A block can hold an if, so a loop can react each time round:

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for i in range(8):
    forward(50, distance=8)
    if distance() < 30:
        led("red")
        print("getting close at step", i)
    else:
        led("green")

Run this in the simulator

The edge of the mat starts 81 cm ahead, so for the first six steps there is room and the LED stays green. At steps 6 and 7 only 24 and 16 cm are left: the LED turns red and the message prints.

Task: count the corners

Drive a square of 30 cm sides with a for loop, printing corner 1, corner 2, corner 3, corner 4 as you go, and finish facing the way you started.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for i in range(4):
    forward(60, distance=30)

Task: play a scale

Use one for loop to play five notes, each for a quarter of a second: 400, 500, 600, 700 and 800 hertz. Work each note out from the loop variable; do not type the notes after the first.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

for i in range(5):
    tone(400, 0.25)

Challenges

  1. Draw a triangle with a for loop (three sides, turn_right(30, angle=120)).
  2. Blink the LED five times using wait(0.2) inside a loop.
  3. Print the 7 times table, from 7 to 70, with one loop.

Past paper questions on this

Real exam questions that test this, each worked through with a program you can run.