Repeating with while

Make a program repeat work for as long as a condition stays True. Write while loops, update a counter so they finish, and recognise (and escape) an infinite loop.

Lesson · 15 min

In this lesson you will

  • Write a while loop and say exactly when it stops
  • Use a counter or running total that changes on every pass
  • Explain why a loop must change something its condition depends on
  • Recognise an infinite loop and a loop that never starts

Computers never get bored, and that’s one of the most useful things about them. Printing the numbers 1 to 5 by hand takes five lines. Printing 1 to a million takes the same few lines, if you use a loop. A loop repeats a block of code, and Python has two kinds. This lesson is about the first: while.

while: keep going as long as…

A while loop looks just like an if: a condition, a colon and an indented block. The difference is what happens after the block. An if runs its block once. A while goes back to the top and checks the condition again, and keeps going round until the condition is False.

n = 1
while n <= 5:
    print(n)
    n = n + 1
print("Done")

Read it as: “while n is at most 5, print n and add one to it”. Each trip through the block is called an iteration. Here’s what happens, one check at a time:

Checkn <= 5?Printsn afterwards
1st1 <= 5 True12
2nd2 <= 5 True23
3rd3 <= 5 True34
4th4 <= 5 True45
5th5 <= 5 True56
6th6 <= 5 Falsestops6

The condition is checked six times but the body runs only five. The last check is the one that fails and lets the program move on to print("Done").

See the loop go round

The flowchart below is the same program. Press Step to move the token one box at a time and watch it travel back up to the diamond after every pass. Then change the start value or the update and run it again.

Loading the interactive graphic…

This flowchart is a while loop. n starts at one, and the diamond asks whether n is at most five.

Every loop needs a way out

Look at the line n = n + 1 (or n += 1). It changes n, so that eventually n <= 5 becomes False. A while loop must change something its condition depends on. If nothing changes, the condition stays True forever and the loop never ends. That’s an infinite loop:

n = 1
while n <= 5:
    print(n)
    # oops: forgot n = n + 1

This would print 1 forever. On this site, a cell that runs for more than about ten seconds is stopped for you and Python restarts, so you can’t get stuck. In other places, pressing Ctrl+C in the terminal stops a runaway program. In the flowchart above, choose the update -= 1 and run it to see the loop heading the wrong way: n gets smaller and smaller, so it is always at most 5.

A loop that never starts

If the condition is False the very first time, the body runs zero times:

n = 10
while n <= 5:
    print("You'll never see this")
    n += 1
print("Skipped straight past the loop")

That’s not an error; sometimes there’s simply no work to do.

Counting and totals

Loops really shine when they build something up. A running total starts at zero and grows on every pass. Here we add 1 + 2 + 3 + … + 10:

total = 0
n = 1
while n <= 10:
    total = total + n
    n = n + 1
print("The sum is", total)

Change the 10 to 100. Python adds a hundred numbers in a blink. (A famous story says the young mathematician Gauss did this one in his head; the answer is 5050.)

When you don’t know how many times

while is the right choice when you don’t know in advance how many iterations you need, only when to stop. How many times must you double 1 before it passes 1000?

value = 1
doublings = 0
while value <= 1000:
    value = value * 2
    doublings = doublings + 1
print(doublings, "doublings gets to", value)

Or a savings plan: you put 50 into a jar every week. How many weeks until you can afford a bike costing 340?

saved = 0
weeks = 0
bike_price = 340
while saved < bike_price:
    saved += 50
    weeks += 1
print(f"After {weeks} weeks you have {saved}, enough for the bike.")

Change bike_price and the weekly amount and predict the answer before each run.

Your turn

Exercise · Python

The magic penny

A magic penny doubles every day: 1 cent on day 0, 2 cents on day 1, 4 cents on day 2, and so on. Use a while loop to find the first day the penny is worth at least one million cents.

When your loop finishes, days should hold that day number and cents the value on that day.

cents = 1
days = 0
target = 1_000_000

# Write a while loop here that doubles cents and counts days


print(f"Day {days}: {cents} cents")

Check yourself

Self-check · 4 questions

while loops

1. When does a while loop stop?
2. n = 1; while n <= 3: n += 1. How many times does the body run?
3. What causes an infinite loop?
4. n = 10; while n < 5: print(n). How many times is n printed?