Textbooks/Engineering Programming With Python/Chapter 3Lite (plain text) version
3Decisions and loops
Version 1 · Technically checked (automated checks only) · 5 source lessons · 8 practice items
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.
Explanation
This chapter is built from 5 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
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 hotOnly 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
- All the branches whose conditions are true will run.
✓ Only the first true branch runs; the rest are skipped. - Indentation is just for looks.
✓ In Python, indentation decides which lines belong to which branch.
Open the full 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
- If the code works for normal values, it works.
✓ Comparison mistakes only show at the boundary. Normal values cannot find them. - Testing 0 and 45 is enough.
✓ Also test one sensor step either side, so you know the boundary is in exactly the right place.
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 °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.
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.
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 2Why 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
- If the mean is normal, the data is fine.
✓ A mean can hide extreme or impossible readings. Check the max, min and plausibility too. - Glitchy readings should be quietly deleted.
✓ Flag, count and report them. A rising glitch count is itself a warning that a sensor is failing.
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.12The 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
- A while loop always runs at least once.
✓ It checks first. If the condition is false at the start, the body never runs. - Infinite loops only happen when you write while True.
✓ Any condition that can never become false, like != on a value that skips past the target, loops for ever.
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
Interactive figure (online). Description: 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.
Interactive figure (online). Description: 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'.
Laboratory
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Studio
Code Lab
Summarise a list of temperature readings in one loop: mean, maximum, minimum and the count above a limit.
Open Code Lab →BUILD level
BUILD: Smart greenhouse, level 2
Read the greenhouse data and flag every hour the temperature left its safe band.
Open BUILD: Smart greenhouse, level 2 →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- A rule is written: if temp_c >= 35: fan = 50, elif temp_c >= 50: fan = 100. What is wrong?
- Nothing
- The fan can never reach 100 %: any temperature ≥ 50 already matches the first test
- It raises a SyntaxError
- Which condition tests whether a reading equals the limit?
- if reading = limit:
- if reading == limit:
- if reading := limit:
- A rule should pass readings from 10 to 60 inclusive, in steps of 1. Which set of tests is best?
- 20, 30, 40
- 9, 10, 11, 59, 60, 61
- 0, 100
- A rule has three thresholds. Using on, just-below and just-above tests for each, how many boundary tests is that? (tests)
- 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)
- What happens with total / len(readings) when readings is []?
- It gives 0
- ZeroDivisionError
- It gives None
- To find the hottest reading in a loop, what should hottest start as?
- 0
- The first reading in the list
- 100
- Which while loop never ends?
- n = 0; while n < 5: n += 1
- n = 10; while n > 0: n -= 2
- n = 1; while n != 10: n += 2
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 verified videos. Nothing loads from YouTube until you press play.
- Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements (Corey Schafer)
- Python Tutorial for Beginners 7: Loops and Iterations - For/While Loops (Corey Schafer)
Chapter summary
- if/elif/else tests in order and runs the first branch that is true, so order the tests carefully.
- Boundary testing checks just below, on, and just above every threshold.
- A for loop can build a total, a count and an extreme in one pass; initialise each one correctly.
- A while loop needs a condition that will eventually become false, or a safety limit.
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.
- 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.
- while loops
- A while loop repeats its body as long as its condition stays true, checking the condition before each pass.
- 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.
- 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.
Definitions from the 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
- The program
- A table of boundary tests with expected and actual results
- One bug you found by testing, and its fix
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- Python Software Foundation. The Python Tutorial. Python Software Foundation. Link ↗
Further reading from the source lessons
- Python tutorial: for statements ↗The official explanation of for loops and range().
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.