Skip to content

Loop patterns: accumulate, count, search

Write and trace the accumulator, counter, running-maximum and search-with-break loop patterns over a list of numbers.

It opens on

This loop adds up five quiz marks and counts the marks that are 12 or more. When it ends, will the count be 2, 3 or 4?

Why it matters

Almost every program that reads data (a gradebook, a log, a sensor) answers its questions with one of a few loop shapes, adding up, counting, keeping the largest so far or searching until a match, and each shape has a start value that is easy to get wrong.

Good to know first

  • for loops and range: a for loop sets the loop variable to each value in turn
  • if: a block runs only when its condition is True
  • Variables and assignment: total = total + m reads the old total, then binds the new one
  • Booleans and comparisons: m >= 12 is True or False

Step by step

  1. Add up and count

    Trace a loop that keeps a running total and a count of the items that pass a test, and give both when it ends.

    On the first pass m is 14, so total becomes 0 + 14 = 14, and 14 >= 12 is True, so passed becomes 1.

    A common mix-up

    Setting total = 0 inside the loop is the same as setting it before.

    In fact: It restarts the total on every pass, so the program would end with only the last mark, 8.

  2. Largest so far

    Write and trace the running-maximum loop, and choose a start value that the list itself can have.

    On the first pass m is 14, and 14 > best is 14 > 14, which is False, so best stays 14.

    A common mix-up

    Starting best at 0 always works.

    In fact: It fails when every item is below 0, and the result 0 is not even in the list.

  3. Search and stop early

    Write and trace a search loop that stops with break at the first match, and say what it reports when there is none.

    On the first pass m is 14, so checked becomes 1, and 14 < 10 is False, so the loop goes on.

    the first row of the trace

    A common mix-up

    Break ends the whole program.

    In fact: It leaves only the loop, and the print after the loop still runs.

Try it

For prices = [6, 4, 10] with a total and a count of the prices over 5, what does the program print?Answer

20 2

Hint: 6 and 10 are over 5, and 6 + 4 + 10 = 20

For marks 6, 12, 9, 12, what does best end at, and on how many passes does it change after the first?Answer

12; once

Hint: 12 > 6 is True, but the later 12 > 12 is False

The same search is for a mark equal to 12 in 14, 9, 12, 17. What does it print?Answer

True 3

Hint: It stops on the third mark

On the third pass m is 17. What are total and passed after it?Answer

Total is 40 and passed is 2.

On the third pass m is 17. Is 17 > best, and what is best after it?Answer

True, so best becomes 17.

Loop patterns: accumulate, count, search

30 minutes every month. No card.