Skip to content
Tactiverge

School/△ Builder/Week 6

for loops: summarise a sensor log

A motor logged a temperature every minute for a shift: 480 readings. How do four lines of Python find the average?

About 40 min · 3 goals · Checked by automated tests

1.Why should I care?

Sensors produce lists of numbers, and engineers need summaries: the mean, the extremes, how many went over a limit. A for loop does the same small job once per reading, whether there are seven readings or seven million.

  • ◇ Store readings in a list and loop over them with for.
  • ◇ Use a running total and a count inside a loop to compute a mean.
  • ◇ Guard against an empty list before dividing.

2.Discover

Choose 'Motor temperature log'. Predict the mean and how many readings go over 50 °C, then run the loop one pass at a time and watch count, total, hottest and over change. Then try 'Empty log': why doesn't the program crash?

Loading the interactive…

Can't use the interactive? Read a description instead

The loop visualiser shows the readings 41.2, 42.0, 43.5, 47.9, 52.3, 49.0, 44.1 °C as bars with a 50 °C limit line. Each step runs one loop pass and updates count, total, hottest, coldest and over. After 7 passes it prints mean 45.714285714285715, max 52.3, min 41.2, over 1. For the empty log the loop never runs and the program prints 'no readings'.

3.Checkpoint: guided practice

Check what you just discovered before going on. Hints appear after a wrong answer.

Practice 1 · a fresh version every time

A loop totals and counts these temperature readings (°C): [18.0, 25.4, 31.8, 31.6, 21.9, 26.6]. What is total / count, in °C?

°C

Practice 2

How many times does the body of for r in readings: run if readings has 7 items?

4.Predict

total = 0.0, then for r in [2.0, 4.0, 6.0]: total = total + r. What is total after the loop?

Guess first. Being wrong here is how the surprise works.

5.Understand

The pattern

readings_c = [41.2, 42.0, 43.5, 47.9, 52.3, 49.0, 44.1]
total = 0.0
for r in readings_c:
    total = total + r
mean_c = total / len(readings_c)
print(f"mean {mean_c:.2f} °C")   # mean 45.71 °C

Set up before the loop, update inside it (indented), use the result after it.

What the loop really does

for r in readings_c: makes r refer to the first reading, runs the indented block, then moves r to the next reading, until the list runs out. The list is not changed. Python also has sum(readings_c) and len(readings_c), but writing the loop yourself is how you add counts, flags and checks.

Empty lists and other edge cases

If the log is empty the loop body never runs, len is 0, and total / len(readings_c) raises ZeroDivisionError. Check first: if len(readings_c) > 0: … else: print("no readings"). A single reading, and readings that are all equal, are good tests too.

Explain it another way

Like a checkout scanning items one by one and adding each price to the running total. Nobody adds the whole trolley at once.

Worked example 1

Readings 3.71, 3.69, 3.66, 3.62 V from a battery. Find the mean with a loop.

total: 0.0 → 3.71 → 7.40 → 11.06 → 14.68 (Python may show tiny float digits). count = 4. mean = 14.68 / 4 = 3.67 V.

Common mix-ups

  • The loop variable r is the position in the list.
    ✓ r is each reading's value. Use enumerate(readings) if you also need the position.
  • A loop over an empty list raises an error.
    ✓ It simply runs zero times. The error comes later, if you divide by the count.

6.Watch

→ Watch how a for loop takes each item of a list in turn, and when Corey reaches for while instead.

Shows for loops over lists, while loops, break and continue: the tools for working through a log of readings.

Length: see YouTube · captions on YouTube · source

Nothing loads from YouTube until you press play.

The video is optional: everything you need is also in the lesson text and the interactive.

7.Practice on your own

Practice, not a test. Wrong answers get a hint and another try.

Practice 3

What happens with total / len(readings) when readings is []?

Practice 4

In a loop that totals readings, where should print(total) go to print the total once?

Practice 5

Readings 20, 22, 24 and 26 °C. What is the mean, in °C?

°C

8.Apply it

Write a program for the 'Motor temperature log' that prints the mean, the count and how many readings are above 50 °C. Test it on an empty list and on a list of one reading, and make sure neither crashes.

9.Reflect

10.Go further

Concepts: Decisions and loops · Lists, dictionaries and tabular data · Describing data