TactivergeLite

Lite / Textbooks / Engineering Programming With Python / Chapter 3

3. Decisions and loops

Version 1 · Technically checked (automated checks only) · 5 source lessons · Full interactive version

Introduction

Programs earn their keep by deciding and repeating. if, elif and else pick a branch from a measurement; the order of the tests and the edge values matter more than you would think. A for loop walks through a log of readings to find the mean, the extremes and how many crossed a threshold; a while loop keeps going until a condition is met, and needs a guaranteed way out.

Figure 3.1. One pass, three answers (described in words)

Five readings shown as bars: 21, 23, 22, 30 and 24, with a dashed threshold at 25. One pass of a loop finds the mean 24, the maximum 30 at index 3, and that 1 reading is above 25.

Explanation

Built from 5 School lessons. Each part is the lesson's own explanation.

3.1 Decisions from measurements: if, elif, else

A battery charger must refuse to charge below 0 °C and above 45 °C. How does a program choose between three actions?

The shape of a decision

def charge_mode(temp_c):
    if temp_c < 0:
        return "BLOCK: too cold"
    elif temp_c <= 45:
        return "CHARGE"
    else:
        return "BLOCK: too hot"

print(charge_mode(-3))    # BLOCK: too cold
print(charge_mode(0))     # CHARGE
print(charge_mode(45.5))  # BLOCK: too hot

Only the first true branch runs

Python checks the if, then each elif in order, and runs the block under the first condition that is True, then skips the rest. else catches everything left. So the cold check comes first, and the elif temp_c <= 45 only needs to handle temperatures that are already known to be 0 or above.

Colons, indentation and comparisons

Each if, elif and else line ends with :, and the lines that belong to it are indented (4 spaces). Comparisons give a bool: <, <=, >, >=, == (equal) and != (not equal). = stores a value and cannot be used in a condition.

Common mix-ups

Open the Lite lesson: Decisions from measurements: if, elif, else

3.2 Test the edges: boundary values

Two versions of a charger rule pass every test at 20 °C. One damages the battery at exactly 45 °C. Which test would have caught it?

Where the bugs live

A rule with thresholds at 0 and 45 °C has two boundaries. For each one, test on it (0, 45), just inside (0.5, 44.5) and just outside (−0.5, 45.5), using the smallest step the sensor can report. Six tests check both edges completely.

Expected values come from the specification

Write down what each test should give before looking at the code, by reading the specification: 'charge when 0 °C ≤ T ≤ 45 °C'. If you work out the expected value by running the code, the test can only confirm the bug.

Boundary tests as asserts

def charge_mode(temp_c):
    if temp_c < 0:
        return "BLOCK: too cold"
    elif temp_c <= 45:
        return "CHARGE"
    else:
        return "BLOCK: too hot"


assert charge_mode(-0.5) == "BLOCK: too cold"
assert charge_mode(0) == "CHARGE"
assert charge_mode(45) == "CHARGE"
assert charge_mode(45.5) == "BLOCK: too hot"
print("boundary tests passed")

Common mix-ups

Open the Lite lesson: Test the edges: boundary values

3.3 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?

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.

Common mix-ups

Open the Lite lesson: for loops: summarise a sensor log

3.4 Count, flag and find extremes

A greenhouse thermometer's daily mean is a perfect 22.0 °C, yet it reported −40 °C and 85 °C. How could a mean hide that?

Count with an if inside a loop

readings_c = [21.4, 21.6, -40.0, 21.9, 22.1, 85.0, 22.0]
hottest = readings_c[0]
coldest = readings_c[0]
glitches = 0
for r in readings_c:
    if r > hottest:
        hottest = r
    if r < coldest:
        coldest = r
    if r < -10 or r > 50:
        glitches += 1
print(hottest, coldest, glitches)   # 85.0 -40.0 2

Why start from the first reading?

Starting hottest = 0 fails when every reading is below 0 °C, as in a freezer log: the 'hottest' would wrongly stay 0. Starting from readings_c[0] (or None, then filling it on the first pass) always gives a real reading. Python's max() and min() do the same and should agree with your loop.

Plausibility checks catch glitches

A greenhouse is never −40 °C. A plausibility band (here −10 to 50 °C) flags readings that are physically impossible, usually from a loose wire, electrical noise or a sensor fault. Flag and count them, report them, and leave them out of the mean, rather than silently averaging them in.

Common mix-ups

Open the Lite lesson: Count, flag and find extremes

3.5 while loops: repeat until it's done

A motor cools by 20 % of its excess heat each minute. How long until it is safe to touch, without knowing the answer in advance?

The cooling simulation

excess_c = 60.0      # motor is 60 °C above the room
minutes = 0
while excess_c > 5:
    excess_c = excess_c * 0.8
    minutes += 1
print(minutes, round(excess_c, 2))   # 12 4.12

The condition is checked before every pass. If it is false at the start, the body never runs.

Every while loop needs progress

Something inside the loop must move it towards stopping: here excess_c shrinks. If nothing changes, the loop runs for ever. For machines, add a guard as well: while excess_c > 5 and minutes < 120: stops even if the model or a sensor misbehaves.

for or while?

Use for when you know what to go through: every reading in a list, each of 10 test cases. Use while when you stop on a condition: until the tank is full, until the error is small, until the user types 'q'. A for loop over a list always ends; a while loop ends only if you make it.

Common mix-ups

Open the Lite lesson: while loops: repeat until it's done

Worked examples

Decisions from measurements: if, elif, else: example 1

Write a fan rule: 100 % at 50 °C or more, 50 % from 35 °C up to 50 °C, otherwise off. What is the fan at 35 °C and at 49.5 °C?

Solution

if temp_c >= 50: fan = 100 / elif temp_c >= 35: fan = 50 / else: fan = 0. At 35: the first test is False, the second True, so 50 %. At 49.5: also 50 %. Order matters: putting the 35 test first would give 50 % even at 80 °C.

Test the edges: boundary values: example 1

A conveyor stops if the load is over 25.0 kg. The scale reads in 0.1 kg steps. Choose boundary tests and their expected results.

Solution

24.9 kg → run, 25.0 kg → run ('over 25' means strictly greater), 25.1 kg → stop. Add a typical value (10 kg → run) and an extreme one (0 kg → run). If the specification had said 'at or over 25 kg', 25.0 would be 'stop'.

for loops: summarise a sensor log: example 1

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

Solution

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.

Count, flag and find extremes: example 1

Freezer log: −19.5, −18.0, −21.2, −18.9 °C. A program starts hottest = 0. What does it report, and how do you fix it?

Solution

No reading is above 0, so hottest stays 0 °C: wrong. Start with hottest = readings[0] = −19.5; the loop then finds −18.0 °C, the real maximum.

while loops: repeat until it's done: example 1

A tank holds 1000 L and drains 15 % of what is left each minute. With a while loop, how many minutes until it is below 500 L?

Solution

1000 → 850 → 722.5 → 614.1 → 522.0 → 443.7. After 5 minutes it is below 500 L, so the loop runs 5 times: while level_l >= 500: level_l = level_l * 0.85; minutes += 1.

Interactive figures, in words

Figure 3.2 from Decisions from measurements: if, elif, else

Choose Version B. Move the temperature slider and watch which return line lights up. Find the exact temperatures where the answer changes. Then switch to Versions A and C: do they ever disagree with the specification?

The boundary tester shows the charge_mode function in three versions and a temperature slider from −10 to 60 °C in 0.5 °C steps. It highlights the line that returns and compares the result with the specification (charge only from 0 °C to 45 °C inclusive). Version B matches everywhere; Version A wrongly blocks at exactly 0 °C; Version C wrongly blocks at exactly 45 °C.

Figure 3.3 from for loops: summarise a sensor log

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?

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'.

The interactive versions are in the full chapter.

Laboratory

These run in a browser on the full site (they need a faster connection). Simulations are simplified educational models.

Practice

Each question links to its Lite lesson, where your answer is checked on our server and a wrong answer gets a hint. Answers are never sent to your device.

  1. A rule is written: if temp_c >= 35: fan = 50, elif temp_c >= 50: fan = 100. What is wrong?
    Answer it in “Decisions from measurements: if, elif, else”
  2. Which condition tests whether a reading equals the limit?
    Answer it in “Decisions from measurements: if, elif, else”
  3. A rule should pass readings from 10 to 60 inclusive, in steps of 1. Which set of tests is best?
    Answer it in “Test the edges: boundary values”
  4. A rule has three thresholds. Using on, just-below and just-above tests for each, how many boundary tests is that?
    Answer it in “Test the edges: boundary values”
  5. 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?
    Answer it in “for loops: summarise a sensor log”
  6. What happens with total / len(readings) when readings is []?
    Answer it in “for loops: summarise a sensor log”
  7. To find the hottest reading in a loop, what should hottest start as?
    Answer it in “Count, flag and find extremes”
  8. Which while loop never ends?
    Answer it in “while loops: repeat until it's done”

Engineering applications

Alarm thresholds

A temperature alarm that fires above 30 °C must be tested at 29.9, 30 and 30.1, because whether the boundary uses > or >= is a real design decision. Most threshold bugs live exactly on the line.

Log summaries

Test rigs produce thousands of readings. A single loop that keeps a running total, a running maximum and a count turns the raw log into the few numbers a report needs.

Watch (optional)

Streaming video uses a lot of data. Everything you need is in the text.

Summary

Glossary

if, elif and else
if runs a block only when its condition is true; elif tests another condition if earlier ones were false; else catches everything left. Field Guide
for loops and range
A for loop runs its body once for each item of a sequence. range(start, stop, step) produces whole numbers from start up to but not including stop. Field Guide
while loops
A while loop repeats its body as long as its condition stays true, checking the condition before each pass. Field Guide
Comparisons and Boolean expressions
Comparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10. Field Guide
Mean and median
The mean is the sum of the values divided by how many there are; the median is the middle value once the values are sorted. Field Guide

Project: The sensor-log checker

Write a program that reads a list of readings, reports their mean, minimum, maximum and the index of the maximum, counts readings outside a safe band, and handles an empty list without crashing. Test it at every boundary of the band.

Deliverables

Write it up on paper or in your own notes. Lite never stores what you write.

References

Further reading from the lessons

← 2. Values, types and formulas4. Functions, tests and debugging →