Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 3 · Lesson 3 · Core

Totals, counters and averages inside loops

Build a running total, count items that match a test and compute an average after the loop.

  • 50 minutes
  • Serves O3
  • Assumes M3.L2

Phase 1: Prepare

Step 1 Warm-up recall

From M3.L2: what stops a while loop?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • build a running total (Foundation);
  • count items that match a condition (Core);
  • compute an average after the loop (Core).

Phase 2: Teach

Step 3 A familiar example

A cashier adds each price to a running total on the till, and counts the items. At the end, the total and the count are the answer. The loop does the same.

Step 4 Clear explanation

A loop becomes useful when it accumulates a result. Start a variable before the loop, change it inside, and use it after.

total = 0
for i in range(1, 5):
    total = total + i
print(total)
10
Start: 00After 1: 11After 2: 32After 3: 63total = total + i
The accumulator pattern: start a total at zero, add to it on every pass, and use it after the loop.

To count items that match a test, put an if inside the loop:

count = 0
for n in range(1, 11):
    if n % 2 == 0:
        count = count + 1
print(count)
5

To find an average, divide the total by the count after the loop ends: 10 / 4 gives 2.5. The starting value matters. A total starts at 0 so that the first addition is right. Put the print line outside the loop to show only the final answer.

Step 5 Worked example (4 marks)

What does this print? s = 0, for k in range(1, 6): s = s + k, print(s)

  1. k takes 1, 2, 3, 4, 5. (1 mark)
  2. s becomes 1, 3, 6, 10, 15. (1 mark)
  3. The print is after the loop, so it shows the last s. (1 mark)
  4. Answer: 15. (1 mark)

Go deeper: the professor's notes

An accumulator starts at 0 and collects a result. A counter adds 1 when a test passes.
Start

total = 0.

Add

Each pass.

Use

After the loop.

Start0Addeach valueTestif neededPrintafter loop
Accumulator

Pattern

VariableStarts at
total0
count0

At work: Orders against a target

212 orders to fill.

  1. Count the orders filled.
  2. Stop when the count reaches 212.

What a careful practitioner decides. Make the stop condition depend on a counter that is really updated.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. A running total should start at:

2. The total of range(1, 4) values (1, 2, 3) is:

3. To count matching items, you use a loop with:

4. The average of a total of 10 over a count of 4 is:

Phase 4: Close

Step 7 Recap

  • Start the total at 0 before the loop.
  • Add inside the loop; print after it.
  • Count with an if and a counter; average after the loop.

Step 8 Exit ticket (ungraded)

Write a loop that adds the numbers 1 to 10 and prints the total.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that counts how many numbers from 1 to 50 are multiples of 7.

In industry: Knight Capital: orders sent without end

On 1 August 2012 an old function on one server was triggered by a repurposed flag. The code that recorded completed orders had been changed, so the function never saw an order as filled and kept sending. In 45 minutes it sent more than 4 million orders to fill 212 customer orders.

Link to this lesson. A counter that never reaches its target is an infinite loop. Always test that the stop condition can be met.

Source: SEC press release 2013-222; Wikipedia, Knight Capital Group

Common mistakes

MistakeWhy it fails
Setting total = 0 inside the loopIt resets on every pass.
Printing inside the loopYou see every step, not the final answer.
Dividing by the wrong countCount the items, not the last value.

Limits. Sums of many decimals can show tiny rounding differences in Python.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · How do you build a running total?
Start0Addeach passPrintafter
Running total

Set total = 0 before the loop, then total = total + value inside it, and print after the loop. This is how a till or a monthly sales sum works.

Card 2 of 3 · Why must the total start at 0 outside the loop?
Outsidetotal = 0InsideresetsResultlast only
Reset error

If you set it inside the loop it resets on every pass and you only keep the last value. Put the starting value before the loop.

Card 3 of 3 · How do you count items that match a test?
Start0TestifAddcount + 1
Counter

Set count = 0, then inside the loop use if test: count = count + 1. For example, count orders over 100 in a week.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards