Lite / Building Machines That Respond / 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?
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.
Predict
total = 0.0, then for r in [2.0, 4.0, 6.0]: total = total + r. What is total after the loop?
- 6.0
- 12.0
- 4.0
Guess first, then reveal
12.0. The loop body runs once per item: 0.0 + 2.0 = 2.0, + 4.0 = 6.0, + 6.0 = 12.0. Dividing by len(...) = 3 gives a mean of 4.0.
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?
What the interactive shows (text version)
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'.
Watch (optional)
Watch for: 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.
“Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops” by Corey Schafer (opens YouTube; streaming video uses a lot of data)
The video is optional. Everything you need is in this lesson's text.
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 °CSet 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
Intuitive
Like a checkout scanning items one by one and adding each price to the running total. Nobody adds the whole trolley at once.
Technical
for iterates over any iterable, binding the loop variable to each element in turn. The accumulator pattern initialises a variable before the loop and updates it each iteration.
Mathematical
Mean x̄ = (1/n) Σ xᵢ. The loop computes Σ xᵢ incrementally: Sₖ = Sₖ₋₁ + xₖ, with S₀ = 0, then divides by n.
Applied
Condition-monitoring systems compute exactly these summaries over each shift's data to decide whether a motor or bearing is running hotter than usual and needs inspection.
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.
Practice
Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.
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.
Reflect
Why is it useful to write the loop yourself even though Python has sum() and len()?
Write your answer on paper or in your own notes. Lite never stores what you write.
Go further
- Python tutorial: for statements
The official explanation of for loops and range().