Thinking in Steps

Repeating with loops

Read a loop, work out how many times it runs, and follow the value it builds up to the end.

Computers are astonishingly good at doing the same thing over and over without complaining. A loop is how you ask for that: you write the step once and say how many times it should happen. Ten stars, a hundred stars or a million stars are all the same amount of writing — only the number changes.

Two things to track

When you follow a loop by hand, keep two things in front of you: how many trips round you have made so far, and what the value is holding right now. Almost every mistake is losing count of one of those two, and the cure is writing both down after every trip rather than keeping them in your head.

Worked example

A program sets a total to 0 and repeats this 3 times: add 5 to the total.

  1. Before any trips: the total is 0.

    The starting value matters, and a loop that begins at 7 rather than 0 ends 7 higher.

Try it together

Now follow this one: a program sets a number to 1 and repeats this 3 times: double the number.

Give the value the number holds after each trip round.

    1.After the first trip, what is the number?

    Have a go

    Have a go on your own. Follow this code by hand. What is total at the end?

    total = 0
    for i in range(0, 6):
        total = total + 5

    Hint: Six trips round the indented line, each one adding 5 to what the last trip left.

    Ready to practice?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet