Repeating Until It Is Done

Repeating while something is true

Follow a loop that keeps going while a condition holds, working out what it leaves behind and how many times it went round.

Every loop so far has known how many times it would go round before it started. A range says so outright, and a list says so by how long it is. There is a second kind of loop that does not know, and cannot: it is written with the word while, followed by a condition, and it keeps going for as long as that condition holds. You use it when the question is not how many times but until what — until the total is large enough, until the value drops below something, until what you were looking for turns up.

Checked before, not after — and nothing makes it stop by itself

The condition is looked at before each trip round, including the very first, so a condition that is already false when the loop is reached means the body never runs at all and everything is left exactly as it was. Once the body does run, the condition is looked at again, and the loop only stops when it fails — which means the value the loop leaves behind is the first one the condition would not have allowed. That is usually past the number in the condition rather than on it. And nothing about a while loop makes it end: something in the body has to change what the condition is watching, and change it in the direction that makes the condition fail. If it does not, the program never finishes, and no error is reported — it simply goes on.

Worked example

What does this program print?

n = 2
while n < 30:
    print(n)
    n = n * 3
  1. n holds 2, and 2 is below 30, so the body runs. It prints 2 and then makes n three times larger, so n holds 6.

    The printing happens before the multiplying because that is the order the two lines are written in. Both are inside the loop.

Try it together

Now one that reports as it goes. Trace it together.

total = 0
weeks = 0
while total < 25:
    total = total + 6
    weeks = weeks + 1
    print(total)

Two variables, one condition. Keep a column for each.

    1.What is the first number printed?

    Have a go

    Have a go on your own. What does this program print?

    n = 1
    while n < 100:
        n = n * 5
    print(n)

    Ready to practise?

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

    Print a worksheet