Week 4 of 105 to 6 hours5 exercises

Week 4: Repeating work with loops

Use for and while loops to repeat steps, build up totals and stop early with break.

By the end of this week you can

  • Loop over a range and over text
  • Write while loops that finish
  • Use break and continue
  • Build totals and counters

for loops and range()

A for loop runs a block once for every item in a sequence. range(n) produces the numbers 0 up to n - 1. range(start, stop) begins at start, and range(start, stop, step) counts in jumps.

The loop variable takes a new value on every pass. You can loop over text too, one character at a time.

end=" " tells print to finish with a space instead of a new line.

Totals and counters

Most loops build up an answer. Start with a variable before the loop (0 for a total, an empty list for a collection), then update it inside. Setting it up inside the loop is a classic mistake: it would reset on every pass.

total += n is a shorter way to write total = total + n.

while loops

A while loop repeats as long as a condition is True. Use it when you do not know in advance how many times you will repeat, for example "keep asking until the answer is valid".

Always make sure something inside the loop eventually makes the condition False. Otherwise the loop never ends. If that happens on this page, the Stop button ends the run.

This is the Collatz sequence. Nobody has proved that every starting number reaches 1, yet it does for every number tried.

break and continue

break leaves the loop immediately. continue skips the rest of this pass and moves to the next one. An else attached to a loop runs only if the loop finished without hitting break; it is rarely needed but good to recognise.

After break, the program carries on with the first line after the loop.

Common mistakes

  • Expecting range(5) to include 5. It gives 0, 1, 2, 3, 4.
  • Resetting a total inside the loop, so it never grows.
  • Writing a while loop whose condition can never become False.
  • Changing a list while looping over it. Loop over a copy or build a new list instead.

Quick recap

  • for loops go over a sequence; range() makes number sequences.
  • Set up totals before the loop and update them inside.
  • while loops need something that ends them.
  • break leaves a loop; continue skips one pass.

Practise this week

Work through the 5 exercises for Week 4. Each one tells you which tests pass, and has a hint and a solution if you get stuck.

Open Week 4 exercises

Check your understanding

Pick an answer for each question, then press Check answers.

  1. How many times does for i in range(3, 8): run?
  2. What does break do inside a loop?
  3. What is the output? total = 0 / for n in [1, 2, 3]: total += n / print(total)
  4. When is a while loop a better fit than a for loop?
  5. What does continue do?

This course is for learning. The Python engine runs in your browser and your code is never sent to us.