Level 2 Building Machines That Respond · Term 1: Computational Thinking
Learners write their first Python programs and learn to break an engineering problem into steps a computer can follow: values and types, engineering formulas as expressions, decisions tested at their boundaries, loops over sensor logs, tested functions and a systematic method for finding bugs, ending with a sensor-log checker.
In this file: 25 lessons across weeks 1–9, with 113 practice questions (questions only, no answers).
Program, analyse and test simple machines that sense their surroundings, make decisions and change their behaviour, all in simulation. Levels describe what you can do, not your age. About About 3 hours a week: roughly 1–1.5 hours of lessons, 1 hour of lab or coding practice and 30 minutes of notebook writing..
Week 1: Computational problem-solving
This week you will
- Decompose an engineering task into smaller jobs and write each as ordered, unambiguous steps.
- Draw and trace a flowchart with a decision and a loop using a trace table.
- Count the input combinations a decision must handle and write a complete rule table.
Break a machine's job into steps
A watering robot is told to 'look after the seedlings'. What exactly should it do at 07:00 tomorrow?
Why it matters
Computers are fast and obedient but have no common sense. Before an engineer writes a line of code, they split the job into pieces and write each piece as steps so precise that a machine cannot misread them. This habit, called computational thinking, is how every controller, from a greenhouse to a Mars rover, gets designed.
Goals
- Decompose an engineering job into smaller jobs that can each be solved and checked.
- Write an algorithm as ordered, numbered steps with quantities, units and a stopping rule.
- Spot a step that is too vague for a computer to follow and rewrite it precisely.
Predict
Which instruction could a watering controller actually follow?
- Water the plants when they look thirsty
- Water until the soil is wet enough
- Open the valve until soil moisture reaches 45 % or 60 s pass
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose 'Seedling watering'. Use Up and Down to put the six steps in order, then mark the two steps a computer could not follow exactly. Check, then compare each vague step with its precise version.
What the interactive shows, in words
The step orderer lists six shuffled steps for automatic watering: read moisture at 07:00; if moisture is 35 % or more skip to the last step; open the valve; keep it open until 45 % or 60 s; close the valve; log the time and moisture. Two steps start vague ('Check the plants in the morning', 'Water until the soil is wet enough'); the task is to order the steps and spot those two.
Understand
Decomposition: one big job, several small ones
'Look after the seedlings' is too big to solve in one go. Split it: sense (read moisture), decide (is it too dry?), act (open and close a valve), record (write a log line). Each piece is small enough to design, test and fix on its own, and different people can work on different pieces.
An algorithm is a precise recipe
An algorithm is a finite list of steps that solves one of those small jobs. Every step must be unambiguous: two people, or a computer, would do exactly the same thing. That usually means naming a quantity and a unit (35 % moisture, 60 s), and saying what happens next.
Every algorithm needs inputs, outputs and an end
Ask three questions of any algorithm. What does it read (inputs)? What does it produce (outputs)? How does it stop? A watering step without a stopping rule floods the tray. Good stopping rules often have a backup, such as 'or 60 s have passed', in case a sensor fails.
Explain it another way: intuitive
Writing an algorithm is like writing directions for a friend who takes everything literally. 'Turn left at the shop' fails if there are two shops. 'Turn left at the second junction, by the red post box' works.
Explain it another way: technical
An algorithm is a finite sequence of well-defined instructions that maps inputs to outputs and terminates. Decomposition splits a problem into sub-problems with clear interfaces: what each piece receives and what it hands on.
Explain it another way: applied
Industrial irrigation controllers are written exactly this way: a schedule, a sensor threshold, a maximum valve-open time and a log. The maximum time is there because moisture sensors do fail, and a stuck-open valve can waste water or drown plants.
Try these examples
Example 1
Decompose 'keep the vaccine fridge between 2 °C and 8 °C' and write the decide step precisely.
The worked solution is in the online lesson.
Common mix-ups
An algorithm has to be written in a programming language.
✓ An algorithm is the method. It can be numbered steps, a flowchart or code; code is just one way to write it down.If a person understands the steps, a computer will too.
✓ People fill gaps with common sense. Computers need every quantity, unit and stopping rule spelled out.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which step is too vague for a computer?
- Read the soil-moisture sensor at 07:00
- Water until the soil is wet enough
- Close the water valve
2. Why do engineers decompose a big job before coding it?
- It makes the program longer
- Each smaller piece can be designed, tested and fixed on its own
- Computers can only run short programs
3. A step says 'Open the valve until moisture reaches 45 %'. What is the safest improvement?
- Remove the step
- Add 'or 60 s have passed, whichever comes first'
- Change 45 % to 100 %
4. For the watering algorithm, which is an output?
- The soil-moisture reading
- The time 07:00
- The log line with the time and final moisture
5. Why must 'Close the water valve' come after 'Keep the valve open until …'?
- It doesn't matter
- Steps run in order, so closing first would mean no water is delivered
- Computers run the last step first
Apply it
Choose a simple machine at home or school (a kettle, an automatic door, a hand dryer). Decompose its job into sense, decide, act and record. Write the decide step as numbered, precise steps with at least one number and unit, and one backup limit.
Reflect
Which vague instruction from your own day would most confuse a computer, and how would you make it precise?
Flowcharts: drawing decisions and loops
A tank controller checks 'is the level equal to 90 L?' after each pump pass. Why might the tank overflow?
Why it matters
Flowcharts are how engineers sketch the logic of a controller before it becomes code. A five-minute trace on paper can reveal a loop that never ends, which on a real pump means a flooded floor.
Goals
- Read and draw a flowchart with actions, a decision and a loop back.
- Trace a flowchart by hand with a trace table to predict how many times a loop runs.
- Explain why a loop's stopping test should use < or >= rather than an exact match.
Predict
The tank starts at 20 L and each pump pass adds 15 L. The flowchart loops while level != 90. What happens?
- It stops at exactly 90 L
- It stops at 95 L
- It never stops: the level goes 80, 95, 110… and is never exactly 90
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start at 20 L with the decision 'level < 90'. Predict how many times the pump runs, then press Step and fill in the trace table. Now switch to 'level != 90' and run it again. Try a start of 30 L too: why does != work there but not from 20 L?
What the interactive shows, in words
The flowchart runner shows: Start (read level) → decision 'level < 90?' → if yes, pump one pass adding 15 L and return to the decision; if no, pump off and stop. A slider sets the starting level and a switch changes the decision to 'level != 90'. From 20 L the trace table reads 20, 35, 50, 65, 80, 95 (stop) with '<', but with '!=' the levels pass 90 and keep rising past the 120 L tank capacity.
Understand
Three shapes are enough
Rounded boxes mark start and end. Rectangles are actions (pump on for one pass). Diamonds are decisions with exactly two exits, yes and no. Arrows say what happens next. An arrow that leads back up to an earlier decision makes a loop.
Trace tables catch bugs on paper
A trace table has one row each time you reach the decision: the value of every variable and whether the test is true. Tracing 20, 35, 50, 65, 80, 95 by hand shows exactly when the loop stops, before any pump is wired up.
Stop on a range, not an exact value
Real quantities rarely land exactly on a target. Steps of 15 L skip over 90 L; a sensor reading of 89.97 is not 90. A stopping test such as level < 90 (keep going while below) always ends; level != 90 can run for ever. Engineers also add a safety limit, such as a maximum number of passes or a high-level float switch.
Explain it another way: intuitive
Imagine filling a bath with a jug that holds 15 L and stopping only when the water is at exactly the 90 L line. You would pour past it and keep going, because 'exactly' never happens.
Explain it another way: technical
A flowchart is a directed graph of process and decision nodes. A loop is a cycle in that graph; it terminates only if the condition on its exit edge must eventually become true. Inequality tests guarantee that for a level that only increases; equality tests do not.
Explain it another way: mathematical
Passes n = ⌈(T − S)/A⌉ for S < T, otherwise 0. Final level = S + n·A, which lies in the range [T, T + A).
Explain it another way: applied
Industrial tanks combine a level sensor with an independent high-level switch that cuts the pump regardless of the controller. Overflow protection is a requirement, not an optional extra.
Derivation: How many passes does the loop need?
The loop runs while
level < target. Start level S, each pass adds A litres.After n passes the level is S + n·A. The loop stops at the first n where S + n·A ≥ target.
Rearrange: n·A ≥ target − S, so n ≥ (target − S) / A.
n must be a whole number of passes, so n is (target − S) / A rounded up. From 20 L with A = 15 L and target 90 L: (90 − 20) / 15 = 4.67 → 5 passes, finishing at 20 + 5 × 15 = 95 L.
If S is already ≥ target, the condition is false at the first check and the pump runs 0 times.
Try these examples
Example 1
Start 40 L, add 25 L per pass, loop while level < 120. Trace it.
The worked solution is in the online lesson.
Common mix-ups
If a loop condition looks sensible, the loop must end.
✓ Only trace tables, or reasoning about how the variable changes, show that it ends. Exact-match tests are a classic trap.Flowcharts are only for beginners.
✓ Engineers still sketch flowcharts and state diagrams to agree on logic before writing safety-critical code.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A tank starts with 55 L of water. The controller runs: while level < 100: level = level + 10 (one pump pass adds 10 L). How many times does the pump run before the loop stops?
Answer: passes
2. In a flowchart, what does a diamond mean?
- An action, such as 'pump on'
- A decision with a yes exit and a no exit
- The end of the algorithm
3. A loop runs while level != 100 and adds 30 L per pass, starting at 0 L. What happens?
- Stops at 100 L
- Stops at 120 L
- Never stops: 90 is followed by 120, so it is never exactly 100
4. Start at 10 L, add 20 L per pass, loop while level < 75. How many passes does the pump make?
Answer: passes
5. Why add 'or 20 passes have run' to the tank loop?
- To make it faster
- So a failed level sensor cannot keep the pump running for ever
- It is needed for the program to start
Apply it
Draw a flowchart for a phone charger that charges in 10 % steps while the battery is below 80 %, then stops. Trace it from 35 %. Then redraw it with an extra decision that stops charging if the battery is hotter than 45 °C.
Reflect
Where else could an exact-match test cause a machine to keep going for ever?
Trace every case with a rule table
A sorting machine reads three yes/no sensors. How many situations must its rules cover, and what happens in the one you forgot?
Why it matters
Machines meet every possible input eventually, including the ones nobody imagined. A rule table that lists every combination is a simple, powerful way to make sure an algorithm never reaches a case with no answer.
Goals
- Count the input combinations a decision must handle.
- Write a complete rule table so every combination has a defined action.
- Use hand tracing of unusual inputs to find gaps in an algorithm.
Predict
A machine reads three yes/no sensors: red?, large?, metal?. How many different combinations can it see?
- 3
- 6
- 8
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the sorting machine at Level 2 and turn the client's brief into the full 8-row rule table: one bin for every combination of red, large and metal. Before you run it, trace two unusual parts by hand (a small red metal part, a large non-red plastic part) and predict their bins.
What the interactive shows, in words
The sorting machine's Level 2 task is a table with 8 rows, one per combination of red (yes/no), large (yes/no) and metal (yes/no). For each row you choose a bin. The lesson can be done on paper: list the 8 combinations, apply the client's brief to each, and check every row has exactly one bin.
Understand
Count the cases first
With k yes/no inputs there are 2^k combinations: 2, 4, 8, 16, … An input with m settings (a selector switch) multiplies the count by m. Counting tells you how many rows a complete rule table, or a complete set of tests, needs.
A rule table is an algorithm
Each row says: for this combination of inputs, do this. Because the rows cover every combination, there is no situation in which the machine has to guess. A rule table is also the easiest way to show a client exactly what the machine will do.
Trace the strange cases
Bugs hide in combinations nobody pictured: a part that is red and metal, a sensor that says large and small at once. Pick the oddest inputs and trace the algorithm by hand. If you cannot say what it does, the algorithm is incomplete.
Explain it another way: intuitive
Like checking every door and window before leaving home: you go through them all, not just the ones you usually use.
Explain it another way: technical
A decision over k Boolean inputs is a function from 2^k input combinations to actions. A truth (rule) table enumerates that function completely. Exhaustive testing is feasible when the input space is this small.
Explain it another way: applied
Safety interlocks on industrial machines are specified with tables like this, then every row is tested. In the sorting machine, a forgotten row means a part ends up in the wrong bin or jams the belt.
Try these examples
Example 1
Brief: 'Metal parts go to bin A. Large non-metal parts go to bin B. Everything else goes to bin C.' Which bin gets a small red plastic part?
The worked solution is in the online lesson.
Common mix-ups
Testing the usual cases proves an algorithm works.
✓ Usual cases are where it was designed to work. Proof comes from covering every case, or at least the strange and boundary ones.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A sorting machine's decision depends on 4 yes/no sensors and one selector switch with 2 positions. How many different input combinations must a complete test table contain?
Answer: rows
2. A rule table for 3 yes/no sensors has only 7 rows. What is the risk?
- None: 7 is close enough
- One combination has no defined action, so the machine's behaviour there is unknown
- The machine will run more slowly
3. Which test input is most likely to expose a gap in a sorting algorithm?
- The most common part
- A part that triggers two rules at once, such as large AND metal
- No part at all, every time
4. A machine has 4 yes/no sensors. How many rows does a complete rule table need?
Answer: rows
Apply it
Finish the sorting machine's Level 2 rule table and run it. Then add a fourth sensor (wet?) to the brief and work out how many rows the new table needs and which bin wet parts should go to.
Reflect
Which row of your rule table did you nearly forget, and why was it easy to miss?
Week 2: Python fundamentals
This week you will
- Write, run and edit a Python program that prints a calculated result with its unit.
- Explain what the interpreter does with each line, top to bottom, and trace a program with a variable table.
Your first Python program: battery runtime
Your sensor node has a 2000 mAh battery and draws 250 mA. Can six lines of Python tell you when it dies?
Why it matters
A calculator answers one question once. A program answers it every time an input changes: a new battery, a new current, a new sensor. Engineers write small programs like this constantly, because they can be checked, shared and rerun.
Goals
- Write, run and edit a Python program that prints a calculated result with its unit.
- Use variables, arithmetic and print, with comments that state units.
- Change an input and rerun the program to answer a design question.
Predict
What does Python print for print(2000 / 250)?
- 8
- 8.0
- 2000 / 250
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the Code Lab and type the battery program from this lesson exactly. Run it. Then change current_ma to 100 and rerun: how long does the node last now? Finally, make it print the runtime in days as well.
What the interactive shows, in words
The Code Lab is an in-browser Python editor. The same exercise works on paper: given capacity 2000 mAh and current 250 mA, compute hours = 2000 / 250 = 8.0 and minutes = 480, then repeat with 100 mA (20.0 h).
Understand
The program
# Battery runtime for a sensor node
capacity_mah = 2000 # battery capacity in mAh
current_ma = 250 # average current draw in mA
hours = capacity_mah / current_ma
print("Runtime:", hours, "h")
print(f"That is {hours * 60:.0f} minutes")Output:
Runtime: 8.0 h
That is 480 minutesWhat each part does
# starts a comment: Python ignores it, people read it. capacity_mah = 2000 creates a variable: a name that stores a value. / divides. print(...) shows values, separated by spaces. The f"..." is an f-string: anything in { } is worked out and put into the text, and :.0f means 'show with 0 decimal places'.
Units live in names and comments
Python does not know what a milliamp is. It only sees numbers. So engineers put units into names (current_ma) and comments. Here mAh ÷ mA leaves hours, so the variable is called hours. If the units in a calculation don't cancel to what you expect, the formula is wrong.
Explain it another way: intuitive
A program is a recipe the computer follows exactly, from the top line down. Variables are labelled jars: put a number in, use it later by name.
Explain it another way: technical
Python is an interpreted language: the interpreter reads each statement, evaluates the expression on the right of =, binds the result to the name on the left, and executes calls like print in order.
Explain it another way: mathematical
Runtime t = Q / I, where Q is charge capacity (mAh) and I is current (mA): 2000 mAh / 250 mA = 8 h. This ideal estimate ignores capacity loss at high current, temperature and the cut-off voltage.
Explain it another way: applied
Wireless sensor nodes are designed around this exact calculation, then made to sleep most of the time: an average of 1 mA instead of 25 mA turns days into months.
Try these examples
Example 1
The node sleeps at 0.5 mA most of the time. What runtime does the program give for current_ma = 0.5?
The worked solution is in the online lesson.
Common mix-ups
print(2000 / 250) prints 8.
✓ It prints 8.0, because / always produces a float in Python 3.The program knows the numbers are in mAh and mA.
✓ Python only sees numbers. Units are your job, which is why they go in names and comments.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A sensor node runs from a 2500 mAh battery and draws a steady 50 mA. A program computes hours = 2500 / 50 and then minutes = hours * 60. What value does minutes hold, in minutes? (Ignore the battery ageing or the voltage dropping.)
Answer: min
2. What does print("3 + 4") show?
- 7
- 3 + 4
- An error
3. What does Python do with # battery capacity in mAh?
- Stores it in a variable
- Ignores it: it is a comment for people
- Prints it
4. Using the same formula, a 3000 mAh battery powers a 25 mA device. How many days is that?
Answer: days
5. Which variable name is best for a current measured in milliamps?
- c
- current
- current_ma
Apply it
Extend the program: add a variable for a safety margin (use only 80 % of the capacity) and print the runtime with and without the margin, each with its unit. Write one comment explaining why engineers keep a margin.
Reflect
What surprised you most about how literally Python follows your program?
Go further (online)
- The Python Tutorial (official)
The official, free introduction to Python, written by its developers.
How the interpreter reads your program
You compute current = voltage / resistance, then change the voltage. Does current change too?
Why it matters
Most early bugs come from imagining the program works like a spreadsheet, where cells update themselves. It doesn't. Knowing exactly what the interpreter does on each line lets you predict a program before running it, which is what debugging really is.
Goals
- Explain that Python runs one line at a time, top to bottom.
- Trace a program by hand with a variable table and predict its output.
- Explain why using a variable before it is assigned raises a NameError.
Predict
voltage_v = 12, then current_a = voltage_v / 48, then voltage_v = 24. What is current_a now?
- 0.25
- 0.5
- It changes back and forth
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Start with 'Battery runtime' and press 'Run next line' one line at a time, watching the variable table. Then try 'Odometer update' (predict distance_m before each step) and 'Used before it exists': which line fails, and why?
What the interactive shows, in words
The program tracer shows a short Python program, highlights the line just run and lists every variable with its value and type after that line. For example, in 'Battery runtime', after line 3 the table shows capacity_mah 2000 (int), current_ma 250 (int), hours 8.0 (float). In 'Used before it exists', line 2 stops with a NameError because resistance_ohm is created only on line 3.
Understand
One line at a time, top to bottom
The interpreter starts at line 1. For an assignment it works out the right-hand side using the values that exist right now, then stores the result under the name on the left. Then it moves to the next line. Nothing goes back up unless a loop or function tells it to.
Assignment is a snapshot
voltage_v = 12
resistance_ohm = 48
current_a = voltage_v / resistance_ohm
print(current_a) # 0.25
voltage_v = 24 # changing it now does not update current_a
print(current_a) # still 0.25To get the new current you must run the calculation again.
Names must exist before you use them
If line 2 uses resistance_ohm but line 3 is where it is created, Python stops at line 2 with NameError: name 'resistance_ohm' is not defined. The fix is to move the assignment above the line that needs it. A typo in a name gives the same error.
Explain it another way: intuitive
The interpreter is a very careful clerk reading a list of instructions, one at a time, with a whiteboard of variable values. It only ever looks at the current line and the whiteboard.
Explain it another way: technical
Python executes statements sequentially. An assignment evaluates its expression in the current namespace and binds the name to the resulting object. A name lookup with no binding raises NameError at runtime.
Explain it another way: applied
Robot control code runs the same idea in a loop: read sensors, compute, act, then compute again with fresh readings. A value computed once at start-up, such as a calibration offset, silently stays stale if the code never recomputes it.
Try these examples
Example 1
Trace: speed = 2; time = 5; distance = speed * time; speed = 3; print(distance).
The worked solution is in the online lesson.
Common mix-ups
Variables update automatically when the values they were made from change, like spreadsheet cells.
✓ A variable holds the value from when its line ran. Recompute it to update it.= in Python means 'is equal to'.
✓ = means 'store'. Equality is tested with ==.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Trace this Python by hand: x = 8; x = x + 1; x = x * 4; x = x - 20; print(x). What number is printed?
Answer:
2. a = 5; b = a * 2; a = 100; print(b). What is printed?
- 10
- 200
- An error
3. Which program raises a NameError?
- x = 3 then print(x)
- print(y) then y = 3
- z = 3 then z = z + 1
4. In Python, what does = mean in total = total + 5?
- total equals total + 5, which is impossible
- Work out total + 5, then store the result in total
- Compare total with total + 5
Apply it
Write a five-line program that computes a robot's distance travelled from speed and time, prints it, changes the speed, recomputes and prints again. Trace it by hand first, then run it in the Code Lab and compare.
Reflect
Describe, in one sentence, the difference between = in maths and = in Python.
Week 3: Variables and data types
This week you will
- Store values in well-named variables with units and update them as counters and running totals.
- Distinguish int, float, str, bool and list, and predict the type of an expression.
- Explain why 0.1 + 0.2 is not exactly 0.3 and compare floats with a tolerance.
Variables that track a changing machine
A robot adds speed × time to its distance fifty times a second. How does one variable keep track of all that?
Why it matters
Machines are full of quantities that change: parts made, distance travelled, energy used. In code, each is a variable updated over and over. Get the update right and the robot knows where it is; get it wrong and the error grows every step.
Goals
- Choose clear variable names that include units.
- Update a variable from its own previous value (counters and running totals).
- Swap two values correctly and explain why the naive swap fails.
Predict
left_c = 31.5, right_c = 29.0, then left_c = right_c, then right_c = left_c. What are they now?
- 29.0 and 31.5 (swapped)
- 29.0 and 29.0
- 31.5 and 31.5
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Run 'Odometer update' and 'Part counter' line by line: which variables change at each step? Then compare 'Swap two sensors (buggy)' with the fixed version and find the exact line where 31.5 is lost.
What the interactive shows, in words
In the program tracer, 'Odometer update' shows distance_m changing 0 → 3.0 → 6.0 → 7.0 as lines 4, 5 and 7 run. 'Swap two sensors (buggy)' shows left_c becoming 29.0 on line 3 and right_c staying 29.0 on line 4, so 31.5 is lost; the fixed version stores 31.5 in spare_c first.
Understand
Names that explain themselves
distance_m, speed_m_per_s, parts_made say what they are and in which unit. Python names use letters, digits and underscores, cannot start with a digit and are case-sensitive (Speed and speed are different). Clear names are the cheapest documentation there is.
Updating from the old value
parts_made = parts_made + 1 reads the old value, adds 1 and stores the result: a counter. distance_m = distance_m + speed_m_per_s * dt_s is a running total. The short form parts_made += 1 does the same. Both need a starting value first, such as parts_made = 0.
Swapping without losing data
left_c, right_c = 31.5, 29.0
left_c, right_c = right_c, left_c
print(left_c, right_c) # 29.0 31.5Python evaluates the whole right side first, then assigns, so nothing is overwritten too early. The step-by-step version needs a spare: spare_c = left_c, then left_c = right_c, then right_c = spare_c.
Explain it another way: intuitive
A counter is like a tally on a whiteboard: rub out the old number and write one more. You have to read it before you rub it out.
Explain it another way: technical
x = x + 1 evaluates x + 1 using the current binding of x, then rebinds x. A tuple assignment a, b = b, a builds the tuple (b, a) before unpacking, so both original values are captured.
Explain it another way: mathematical
Dead reckoning: d_n = d_(n−1) + v·Δt. After n steps at constant speed, d_n = d_0 + n·v·Δt. Each small error in v or Δt is added every step, so the position error grows with time.
Explain it another way: applied
Wheel odometry on a mobile robot is exactly this running total, updated many times a second from wheel encoders. Because errors accumulate, robots correct it with other sensors such as cameras or GPS.
Try these examples
Example 1
distance_m = 0; speed 1.5 m/s for two steps of 2 s, then 0.5 m/s for one step of 2 s. Final distance?
The worked solution is in the online lesson.
Common mix-ups
a = b then b = a swaps two values.
✓ The first line overwrites a, so its old value is gone. Use a spare or a, b = b, a.Short names like x and t make code tidier.
✓ In engineering code, names with units (time_s, temp_c) prevent mistakes that cost far more than a few keystrokes.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A robot starts with distance_m = 0.0 and its loop runs distance_m = distance_m + speed_m_per_s * dt_s exactly 7 times, with speed_m_per_s = 2 and dt_s = 0.1. What is distance_m at the end, in metres?
Answer: m
2. Which lines correctly swap a and b?
- a = b then b = a
- a, b = b, a
- b = a then a = b
3. Which is a valid Python variable name?
- 2nd_reading
- second-reading
- second_reading
4. count = 0, then count += 1 runs 3 times, then count = count * 2 runs once. What is count?
Answer:
5. A program runs total_wh = total_wh + 5 but never set total_wh before. What happens?
- total_wh becomes 5
- NameError: total_wh is not defined
- total_wh becomes 0
Apply it
Write a program for a conveyor: start parts_made and rejects at 0, then record eight parts (three of them rejected) with updates. Print the number of good parts and the reject rate as a percentage. Trace it by hand, then run it.
Reflect
Why does a robot's dead-reckoning position drift further from the truth the longer it runs?
int, float, str and list
A sensor file says "23.5". Add 0.4 and Python refuses. Why is a number in quotes not a number?
Why it matters
Data from sensors, files and keyboards arrives as text. Calculations need numbers. Knowing the type of every value, and converting at the right moment, prevents a whole family of crashes and silent errors.
Goals
- Distinguish int, float, str, bool and list values and predict the type of an expression.
- Use //, % and / correctly, for example to split seconds into minutes and seconds.
- Convert text to numbers with int() and float() and explain when conversion fails.
Predict
What type is the result of 6 / 3 in Python 3?
- int (2)
- float (2.0)
- str ('2')
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Predict the value and type of each expression before you click it. Start with 7 / 2, 7 // 2 and 6 / 3, then the string ones. In 'Try your own numbers', find two numbers where // and / give the same value but different types.
What the interactive shows, in words
The type inspector lists expressions with their Python results: 7 / 2 → 3.5 (float); 6 / 3 → 2.0 (float); 7 // 2 → 3 (int); 135 // 60 → 2 and 135 % 60 → 15 (int); "7" + "2" → '72' (str); "23.5" + 0.4 → TypeError; float("23.5") + 0.4 → 23.9; int("4.2") → ValueError; int(9.99) → 9. A second panel computes any two numbers with any operator and shows the result and its type.
Understand
Five types you will use every day
int: whole numbers, 135. float: numbers with a decimal point, 23.5. str: text in quotes, "23.5". bool: True or False, the result of a comparison. list: an ordered collection, [21.5, 22.0, 22.4]. Ask type(x) to check.
Three kinds of division
seconds = 135
minutes = seconds // 60 # 2 (floor division)
leftover_s = seconds % 60 # 15 (remainder)
print(f"{minutes} min {leftover_s} s")
print(7 / 2) # 3.5 (always a float)// and % together split a quantity into whole units and what is left over: seconds into minutes, parts into boxes.
Text is not a number until you convert it
"23.5" + 0.4 raises a TypeError. float("23.5") + 0.4 gives 23.9. int("42") gives 42, but int("4.2") raises a ValueError, and int(9.99) chops to 9, it does not round. With strings, + joins text: "7" + "2" is "72".
Explain it another way: intuitive
A type is the kind of thing a value is. You can add two numbers or join two words, but adding a number to a word makes no sense, so Python stops and says so.
Explain it another way: technical
Python is dynamically but strongly typed: values carry their type, names do not. Operators dispatch on operand types; int and float mix (the result is float), but str and float do not mix under +.
Explain it another way: applied
Data loggers and serial sensors send readings as text, often with stray characters. Embedded and data code always has a conversion step that can fail, and the failure must be handled rather than ignored.
Try these examples
Example 1
A process takes 7384 s. Write it as hours, minutes and seconds with // and %.
The worked solution is in the online lesson.
Common mix-ups
int(9.99) rounds to 10.
✓ int() chops the fraction: int(9.99) is 9. Use round() to round./ gives an int when the answer is whole.
✓ In Python 3, / always gives a float: 6 / 3 is 2.0.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A machine makes 26 parts and packs them in boxes of 12. What does Python give for 26 // 12 (full boxes)?
Answer: parts
2. What is the type of 7 // 2?
- int
- float
- str
3. reading = "23.5". Which line gives the number 23.9?
- reading + 0.4
- float(reading) + 0.4
- int(reading) + 0.4
4. What does "7" + "2" give?
- 9
- "72"
- An error
5. A machine makes 250 parts and packs 12 per box. How many parts are left over (250 % 12)?
Answer: parts
Apply it
Write a program that takes a total run time in seconds (try 7384) and prints it as 'h min s'. Then add a line that reads a battery voltage stored as the text "3.71", converts it and prints whether it is below 3.5 V.
Reflect
Which type mistake do you think you are most likely to make, and how will you catch it?
Go further (online)
- Python tutorial: numbers and text
The official tutorial's first look at numbers, strings and lists.
Why 0.1 + 0.2 is not 0.3
Ask Python whether 0.1 + 0.2 == 0.3 and it says False. Is your computer broken?
Why it matters
Every engineering program uses floats, and every float is a tiny bit approximate. Usually that doesn't matter. It matters a lot when code tests for exact equality, or adds a small step thousands of times. Knowing why stops a whole class of mysterious bugs.
Goals
- Explain why many decimal fractions cannot be stored exactly in binary.
- Predict when floating-point error appears and how it accumulates in a loop.
- Compare floats with a tolerance (math.isclose or abs(a − b) < tol) instead of ==.
Predict
What does Python print for 0.1 + 0.2?
- 0.3
- 0.30000000000000004
- 0.29999999999999999
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Add 0.1 one time, two times, three times… When does == first say False? Find a number of additions where == says True again. Then look at what Python really stores for 0.1, 0.5 and 0.25: which ones are exact?
What the interactive shows, in words
The float explorer adds 0.1 to a total n times and prints the result as Python does: n = 1 gives 0.1, n = 2 gives 0.2, n = 3 gives 0.30000000000000004 (== 0.3 is False, math.isclose is True), n = 8 gives 0.7999999999999999. A second panel shows the exact stored values: 0.1 is 0.1000000000000000055511151231257827021181583404541015625, while 0.5 and 0.25 are exact.
Understand
See it in code
import math
total = 0.1 + 0.2
print(total) # 0.30000000000000004
print(total == 0.3) # False
print(math.isclose(total, 0.3)) # True
print(abs(total - 0.3) < 1e-9) # TrueThe last two lines are how engineers compare measured or computed values: within a stated tolerance.
Errors can accumulate
One addition is off by about 10⁻¹⁷. Add 0.1 a million times and the errors can add up to something you can see. A timer that does t = t + 0.1 every tick slowly drifts. The cure is to count whole ticks in an int and compute t = ticks * 0.1 when needed.
Practical rules
Never test floats with ==; use a tolerance that means something physically (1 mV, 0.01 °C). Keep money and counts in ints (pence, millimetres, ticks). Round only for display, with round() or an f-string such as f"{x:.2f}", not in the middle of a calculation.
Explain it another way: intuitive
Try writing 1/3 as a decimal on a strip of paper with room for ten digits: 0.3333333333. It is close, but not exact. The computer has the same problem with 1/10, just in binary.
Explain it another way: technical
Python floats are IEEE 754 double precision: 1 sign bit, 11 exponent bits and a 52-bit fraction (53 significant bits). Each arithmetic operation is correctly rounded, so the relative error per operation is at most about 1.1 × 10⁻¹⁶.
Explain it another way: mathematical
A rational p/q (in lowest terms) has a terminating binary expansion only if q = 2ᵏ. For 1/10, q = 2 × 5, so the expansion is infinite and periodic, and the stored value differs from 0.1 by about 5.55 × 10⁻¹⁸.
Explain it another way: applied
Test code for sensors and simulations always compares within a tolerance, for example assert abs(measured_v - 3.3) < 0.005. Firmware on small chips often avoids floats entirely and stores millivolts or millimetres as integers.
Derivation: Why 0.1 cannot be written exactly in binary
In base 10, 1/3 = 0.333… never ends, because 3 does not divide any power of 10. A fraction ends in base 10 only if its denominator is built from 2s and 5s (the factors of 10).
In base 2, a fraction ends only if its denominator is a power of 2. 1/2 = 0.1₂ and 1/4 = 0.01₂ are exact, so 0.5 and 0.25 are stored perfectly.
0.1 = 1/10 = 1/(2 × 5). The factor 5 is not a power of 2, so in binary 0.1 repeats for ever: 0.000110011001100…₂.
A Python float keeps 53 binary digits, so it stores the nearest value it can: 0.1000000000000000055511151231257827… That error is tiny (about 5.6 × 10⁻¹⁸) but not zero.
0.1 + 0.2 adds two rounded values and rounds again. The result lands one step above the float nearest to 0.3, so
0.1 + 0.2 == 0.3is False whilemath.isclose(0.1 + 0.2, 0.3)is True.
Try these examples
Example 1
A test asserts led_resistor(3.3, 2.0, 10) == 130 and fails. The function returns 129.99999999999997. Is the function wrong?
The worked solution is in the online lesson.
Common mix-ups
0.1 + 0.2 != 0.3 means Python has a bug.
✓ It is how binary floating point works in almost every language. Python is doing exactly what IEEE 754 specifies.Floats are random or unreliable.
✓ Floats are deterministic and very accurate (about 16 significant digits). Only exact equality tests and long accumulations need care.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which test is the right way to check that a computed voltage v is 3.3 V?
- v == 3.3
- abs(v - 3.3) < 0.001
- v = 3.3
2. Which of these decimals is stored exactly as a Python float?
- 0.1
- 0.3
- 0.25
3. A regulator should output 2.5 V. A test reads 2.502 V. What is the absolute error, |measured − expected|, in millivolts?
Answer: mV
4. What does print(0.1 * 3 == 0.3) show?
- True
- False
- An error
5. A timer adds 0.1 s every tick. What is the most reliable design?
- Keep adding 0.1 to a float
- Count ticks in an int and compute ticks * 0.1 when needed
- Round the float after every addition
Apply it
Write a program that adds 0.1 one thousand times in a float and also counts ticks in an int. Print both totals, their difference, and whether math.isclose says they match. Write one sentence on which you would trust in a timer.
Reflect
Where in a real machine would a tiny float error be harmless, and where could it matter?
Go further (online)
- Floating-point arithmetic: issues and limitations
The official Python tutorial's own explanation of this exact surprise.
Week 4: Mathematical expressions
This week you will
- Translate an engineering formula into a correct Python expression, respecting operator precedence.
- Rearrange a formula for the unknown and convert inputs to consistent units in code.
- Use the math module (sqrt, sin, cos, radians) in a calculation with units stated.
Translate a formula into Python
Two programs compute a voltage divider's output. One says 3.4 V, the other 2211 V. Which pair of brackets is missing?
Why it matters
The maths in a textbook uses layout to show order: a fraction bar, a raised power. Code is one flat line, so the order has to be spelled out with precedence and brackets. This is where engineering mathematics meets programming, and where many real calculation bugs start.
Goals
- Translate an engineering formula into a correct Python expression with named variables and units.
- Apply Python's operator precedence: brackets, **, unary minus, * / // %, then + −.
- Check an expression with a units check and an estimate.
Predict
With v_in = 5, r1 = 1000 and r2 = 2200, what does v_in * r2 / r1 + r2 give?
- 3.4375
- 2211.0
- An error
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Pick 'Voltage divider' and step through each expression: in which step does the wrong one go astray? Then try 'Kinetic energy' (is 1 / 2 * m * v ** 2 right?) and 'Average speed' (why is averaging the two speeds wrong?).
What the interactive shows, in words
The precedence explorer shows a formula, sliders for its inputs, and several Python expressions. For the chosen expression it lists every evaluation step. Example, voltage divider with 5 V, 1000 Ω, 2200 Ω: v_in * r2 / (r1 + r2) → 5 * 2200 / 3200 → 11000 / 3200 → 3.4375 (matches); v_in * r2 / r1 + r2 → 11000 / 1000 + 2200 → 11.0 + 2200 → 2211.0 (does not match).
Understand
Python's order of operations
- Brackets. 2. Powers
**(worked right to left). 3. Unary minus, so-3 ** 2is-9. 4.*,/,//,%from left to right. 5.+,-from left to right. When in doubt, add brackets: they cost nothing and show your intent.
A translation recipe
- Name each quantity with its unit:
mass_kg,speed_m_per_s. 2. Replace a fraction bar with/and wrap the whole top and bottom in brackets. 3. Write powers with**. 4. Run it with numbers you can check by hand.
mass_kg = 1.2
speed_m_per_s = 3
energy_j = 0.5 * mass_kg * speed_m_per_s ** 2
print(round(energy_j, 2)) # 5.4Units check and estimate
For E = ½mv²: kg × (m/s)² = kg·m²/s² = J, so the formula is consistent. Estimate: ½ × 1 × 3² ≈ 4.5, close to 5.4. If an answer is out by a factor of 1000 or has the wrong unit, a conversion or bracket is missing.
Explain it another way: intuitive
A formula on paper uses its shape (a fraction bar, a small raised 2) to show what happens first. Code has no shape, so brackets do that job.
Explain it another way: technical
Python parses an expression into a tree using precedence and associativity, then evaluates it depth-first, left operand before right. is right-associative: 2 3 2 = 2 9 = 512.
Explain it another way: mathematical
V_out = V_in·R₂/(R₁ + R₂). With 5 V, 1 kΩ and 2.2 kΩ: 5 × 2200 / 3200 = 3.4375 V. Check the limits: if R₂ → 0, V_out → 0; if R₁ → 0, V_out → V_in. Both are physically right.
Explain it another way: applied
Voltage dividers scale a battery voltage down so a microcontroller can measure it. A bracket slip in the scaling code makes the robot think its battery is full when it is nearly flat.
Derivation: Average speed is total distance over total time
A robot drives d₁ = 120 m in t₁ = 40 s, then d₂ = 80 m in t₂ = 60 s.
Average speed means one steady speed that covers the same total distance in the same total time: v = (d₁ + d₂) / (t₁ + t₂).
Substitute: v = (120 + 80) / (40 + 60) = 200 m / 100 s = 2.0 m/s.
Averaging the two speeds gives (3.0 + 1.33) / 2 ≈ 2.17 m/s, which is wrong because the robot spends longer on the slow leg.
In Python the brackets carry the fraction bar:
(d1_m + d2_m) / (t1_s + t2_s). Without them,d1_m + d2_m / t1_s + t2_sgives 120 + 2 + 60 = 182.0, with meaningless units.
Try these examples
Example 1
Write F = C × 9/5 + 32 in Python and check it at 100 °C.
The worked solution is in the online lesson.
Common mix-ups
Python works out a line from left to right, whatever the operators.
✓ Precedence comes first: ** before * and /, which come before + and −. Left to right only applies within the same level.Extra brackets are bad style.
✓ Brackets that show intent are good style in engineering code, especially around a whole numerator or denominator.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which Python line correctly computes V_out = V_in·R2/(R1 + R2)?
- v_out = v_in * r2 / r1 + r2
- v_out = v_in * r2 / (r1 + r2)
- v_out = (v_in * r2 / r1) + r2
2. What does Python give for -3 ** 2?
- 9
- -9
- An error
3. A 2 kg robot moves at 36 km/h. Convert to m/s (divide by 3.6), then use E = 0.5 * m * v ** 2. What is its kinetic energy, in joules?
Answer: J
4. Is 1 / 2 * m * v ** 2 a correct translation of ½mv² in Python 3?
- Yes: 1 / 2 is 0.5 and the rest is left to right
- No: 1 / 2 is 0 in Python
- No: it computes 1 / (2 · m · v²)
5. A robot drives 300 m in 100 s, then 100 m in 100 s. What is its average speed, in m/s?
Answer: m/s
6. Someone writes power_w = voltage_v / current_a. What does a units check say?
- Fine: V/A is watts
- Wrong: V/A is ohms; power is V × A
- Fine if the numbers are small
Apply it
Translate three formulas you know (for example density = mass/volume, P = V·I, and the voltage divider) into Python with named variables and units. For each, write one test value you can check by hand and run it.
Reflect
Which precedence rule surprised you most, and how will you protect yourself from it?
Go further (online)
- Python reference: operator precedence
The official table of which operators bind tighter.
Rearrange the formula, then compute: an LED resistor
An LED needs 20 mA from a 5 V supply. Ohm's law says R = V/I. Which V, and why does the answer come out 1000 times too small?
Why it matters
Datasheets give you most quantities; the design gives you the one you need to find. Rearranging the formula, converting units and checking the result is the core loop of engineering calculation, and a program makes it repeatable for every LED on the board.
Goals
- Rearrange a formula so the unknown is on its own before coding it.
- Convert inputs to consistent SI units (mA to A) inside the program.
- Write a short calculator program that prints a result with its unit and a power check.
Predict
A 5 V supply drives an LED that drops 2.0 V, at 20 mA. What resistor is needed?
- 0.15 Ω
- 150 Ω
- 250 Ω
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the Code Lab and type the LED resistor calculator from this lesson. Run it and check you get 150 Ω and 0.060 W. Then change the supply to 3.3 V and the LED to a 3.0 V blue one at 10 mA: what resistor do you need now?
What the interactive shows, in words
The Code Lab exercise can be done by hand: R = (5.0 − 2.0) / 0.020 = 150 Ω and P = 3.0 × 0.020 = 0.060 W; with 3.3 V, a 3.0 V LED and 10 mA, R = 0.3 / 0.010 = 30 Ω (choose the next standard value up, such as 33 Ω) and P = 0.003 W.
Understand
The calculator
v_supply = 5.0 # V
v_forward = 2.0 # V, from the LED datasheet
current_ma = 20 # mA, wanted LED current
current_a = current_ma / 1000
r_ohm = (v_supply - v_forward) / current_a
power_w = (v_supply - v_forward) * current_a
print(f"R = {r_ohm:.0f} ohm, P = {power_w:.3f} W")Output: R = 150 ohm, P = 0.060 W
Convert first, in one place
Datasheets mix units: mA, kΩ, mV. Convert everything to base SI units (A, Ω, V) once, near the top, in a clearly named variable such as current_a. Then every formula below can be written exactly as it appears in a textbook.
Pick a real part and check it
Resistors come in standard values, such as 120, 150 and 180 Ω. If the calculation gives 140 Ω, choose the next value up (150 Ω), so the current is slightly lower, never higher. Then check the power against the resistor's rating. This lesson is calculation only: any real circuit is built in the circuit simulator first.
Explain it another way: intuitive
The supply pushes with 5 V, the LED takes 2 V of that, and the resistor must 'use up' the other 3 V while letting just the right flow of current through.
Explain it another way: technical
Rearranging keeps an equation balanced: whatever you do to one side, do to the other. Coding the rearranged form, with inputs converted to SI units, makes the program a direct, checkable copy of the derivation.
Explain it another way: mathematical
R = (V_s − V_f)/I. Sensitivity: if V_f is 0.2 V higher than expected, the current with R fixed is I = (V_s − V_f)/R, which drops by 0.2 / 150 ≈ 1.3 mA. That is small, which is why one resistor works across LEDs of the same type.
Explain it another way: applied
Indicator LEDs on every control panel use this calculation. Too small a resistor overheats or burns out the LED; too large and it is too dim to see in daylight.
Derivation: From Ohm's law to the LED resistor formula
Ohm's law for the resistor: V_R = I · R, with V_R in volts, I in amps and R in ohms.
Divide both sides by I to make R the subject: R = V_R / I.
The LED and the resistor are in series across the supply, so their voltages add: V_supply = V_forward + V_R, giving V_R = V_supply − V_forward.
Substitute: R = (V_supply − V_forward) / I.
Example: (5.0 V − 2.0 V) / 0.020 A = 3.0 / 0.020 = 150 Ω. Power in the resistor: P = V_R · I = 3.0 × 0.020 = 0.060 W, well under a common 0.25 W rating.
Try these examples
Example 1
A 12 V supply drives a white LED (3.0 V) at 15 mA. Find R and P.
The worked solution is in the online lesson.
Common mix-ups
Use the supply voltage in R = V / I for an LED resistor.
✓ Use the voltage across the resistor, V_supply − V_forward.Unit conversions can be done in your head while reading the code.
✓ Do them in code, once, in named variables, so every reader and every rerun gets them right.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. An LED with a forward voltage of 1.8 V should carry 15 mA from a 9 V supply. Using r_ohm = (v_supply - v_forward) / (current_ma / 1000), what resistance is needed, in ohms?
Answer: Ω
2. Rearrange V = I · R to find I.
- I = V · R
- I = V / R
- I = R / V
3. A program does r = (5 - 2) / 20 with the current in mA. What goes wrong?
- Nothing
- It gives 0.15 Ω, 1000 times too small, because 20 mA must be 0.020 A
- It gives a TypeError
4. A resistor drops 4.5 V at 0.030 A. What power does it dissipate, in watts?
Answer: W
Apply it
Turn the calculator into a table: for supplies of 3.3, 5, 9 and 12 V, print the resistor and power for a red LED (2.0 V, 15 mA). Mark any case where the power is above 0.125 W. Then build one case in the circuits lab to confirm the current.
Reflect
Why is it better to convert units once at the top of a program than inside each formula?
The math module: roots, angles and radians
A 2.4 m ramp rises at 30°. Python says its height is −2.37 m. What did the program forget?
Why it matters
Ramps, braces, robot arms and wheels all need square roots and angles. Python's math module has them, but with one famous trap: its trigonometry works in radians. Mixing up degrees and radians has caused real engineering errors.
Goals
- Import and use math.sqrt, math.sin, math.cos, math.radians and math.pi.
- Convert degrees to radians before using trigonometric functions.
- Compute lengths and heights in simple structures, with units, and sanity-check them.
Predict
What does math.sin(30) give in Python?
- 0.5
- About −0.988
- An error: 30 is not an angle
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose 'Ramp height (math)'. Compare the version with math.radians to the one without, at several angles: is the wrong one ever right? Then choose 'Diagonal brace (math)' and find out why √w + √h is not the brace length.
What the interactive shows, in words
The precedence explorer's ramp preset compares length * math.sin(math.radians(angle)) with length * math.sin(angle). For 2.4 m at 30° the first gives 1.1999999999999997 m (matches 1.2 m) and the second gives −2.3712758978228683 m (wrong). The brace preset shows math.sqrt(0.3 ** 2 + 0.4 ** 2) = 0.5 m, while math.sqrt(w ** 2) + math.sqrt(h ** 2) gives 0.7 m.
Understand
Import, then call
import math
length_m = 2.4
angle_deg = 30
height_m = length_m * math.sin(math.radians(angle_deg))
print(round(height_m, 3)) # 1.2
w_m, h_m = 0.3, 0.4
brace_m = math.sqrt(w_m ** 2 + h_m ** 2)
print(brace_m) # 0.5import math once at the top, then use math. before each function.
Radians in, radians out
math.sin, math.cos and math.tan expect radians, and math.atan2 returns radians. Convert at the boundary: math.radians(deg) going in, math.degrees(rad) coming out. Name variables _deg or _rad so the unit is never in doubt.
Sanity checks for geometry
A ramp's height must be less than its length. A diagonal must be longer than either side but shorter than both added together. sin and cos are always between −1 and 1. A negative height or a brace shorter than a side means a unit or bracket error.
Explain it another way: intuitive
Degrees and radians are like inches and centimetres for angles. The math module only speaks radians, so you translate first.
Explain it another way: technical
math functions are implemented by the platform's C maths library on IEEE doubles. math.radians(x) returns x·π/180; results carry tiny rounding errors, so sin(π/6) prints as 0.49999999999999994.
Explain it another way: mathematical
Opposite = hypotenuse × sin θ; adjacent = hypotenuse × cos θ; hypotenuse = √(a² + b²). For a 0.3 m × 0.4 m frame the brace is √(0.09 + 0.16) = √0.25 = 0.5 m.
Explain it another way: applied
A robot arm's tip position is x = L·cos θ, y = L·sin θ for each link. Feeding encoder angles in degrees to cos and sin would put the gripper somewhere completely different.
Derivation: Degrees to radians
A full turn is 360°. Measured as arc length on a circle of radius 1, a full turn is the circumference 2π, so 360° = 2π rad.
Divide both sides by 360: 1° = 2π/360 = π/180 rad.
So θ_rad = θ_deg × π / 180. For 30°: 30 × π / 180 = π/6 ≈ 0.5236 rad.
math.radians(30) does exactly this calculation. Then 2.4 × sin(π/6) = 2.4 × 0.5 = 1.2 m.
Try these examples
Example 1
A wheelchair ramp may rise at most 1 in 12. What angle is that, and how long a ramp reaches a 0.5 m step?
The worked solution is in the online lesson.
Common mix-ups
math.sin(30) gives sin 30°.
✓ It gives sin of 30 radians. Convert with math.radians first.√(a² + b²) = a + b.
✓ Square roots do not split over addition: √(9 + 16) = 5, not 3 + 4 = 7.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A loading ramp is 2.7 m long and rises at 5° to the floor. Python computes height_m = 2.7 * math.sin(math.radians(5)). What is the height, in metres?
Answer: m
2. Which line correctly computes cos of 60°?
- math.cos(60)
- math.cos(math.radians(60))
- math.radians(math.cos(60))
3. A rectangular frame is 80 cm wide and 115 cm tall. Python computes brace_cm = math.sqrt(80 ** 2 + 115 ** 2). How long is the diagonal brace, in centimetres?
Answer: cm
4. Why is math.sqrt(w ** 2) + math.sqrt(h ** 2) not the brace length?
- It is the same thing
- It simplifies to w + h, which is longer than the real diagonal
- It is shorter than the diagonal
5. What is 45° in radians, to 3 decimal places?
Answer: rad
Apply it
Write a program that prints the tip position (x, y) of a 0.25 m robot arm link for angles 0°, 30°, 60° and 90°. Check that x² + y² is always 0.25² (to float precision), then compare with the kinematics lab.
Reflect
How will you make sure, in every program you write, that an angle is in the unit the function expects?
Go further (online)
- Python math module
Every function in math, with notes on units and edge cases.
Week 5: Conditional statements
This week you will
- Use if / elif / else to choose an action from a measured value.
- Combine conditions with and, or and not to express a safety interlock.
- Choose boundary tests from a specification and use them to find a < versus <= bug.
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?
Why it matters
Every responsive machine makes decisions: heater on or off, charge or wait, sort left or right. In code, each decision is an if statement built from a measurement and a threshold. Get the order or the boundary wrong and the machine misbehaves exactly at its limits.
Goals
- Use if / elif / else to choose one action from a measured value.
- Explain that only the first true branch runs, so the order of conditions matters.
- Use comparison operators (<, <=, >, >=, ==, !=) and indentation correctly.
Predict
In the charge_mode function, what does charge_mode(0) return?
- BLOCK: too cold
- CHARGE
- BLOCK: too hot
Write down your guess and your reason. The reveal is in the online lesson.
Discover
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?
What the interactive shows, in words
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.
Understand
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.
Explain it another way: intuitive
It is a set of doors tried in order. You walk through the first one that opens and never try the others.
Explain it another way: technical
An if/elif/else chain is evaluated top to bottom; each condition is converted to bool, and the first truthy branch executes. Indentation defines the block structure in Python.
Explain it another way: applied
Lithium-ion battery management systems really do block charging outside a temperature window (a common one is 0–45 °C, but each cell's datasheet sets its own), because charging a cold cell can damage it permanently.
Try these examples
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?
The worked solution is in the online lesson.
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.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A cooling fan is set by: if temp_c >= 45: fan = 100, elif temp_c >= 35: fan = 50, else: fan = 0. What is fan, in %, when temp_c = 44.5?
Answer: %
2. 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
3. Which condition tests whether a reading equals the limit?
- if reading = limit:
- if reading == limit:
- if reading := limit:
4. When does the else block in charge_mode run?
- Always
- Only when every condition above it was False
- When the temperature is exactly 45
Apply it
Write classify(level_pct) for a water tank: 'LOW' below 20 %, 'OK' from 20 % to 90 % inclusive, 'HIGH' above 90 %. Print it for 0, 19.5, 20, 90 and 90.5 and check each by hand.
Reflect
Why do you think safety checks are usually written first in an if/elif chain?
and, or, not: safety interlocks in code
A press may run only if the guard is shut, an operator is present and there is no fault. Can one line of Python say all that?
Why it matters
Interlocks are the code that keeps people safe around machines. They are nearly always several conditions joined together. Writing them clearly, and checking every combination, is one of the most important habits a controls engineer has.
Goals
- Combine conditions with and, or and not, and know their order (not, then and, then or).
- Turn a worded safety rule into a Boolean expression and test it on every combination.
- Use a chained comparison such as 0 <= temp_c <= 45 for a range.
Predict
guard_closed = True, operator_present = False, fault = False. What is guard_closed and operator_present and not fault?
- True
- False
- An error
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the logic lab, build guard AND operator AND (NOT fault). Toggle the three inputs through all 8 combinations and record which ones light the output. Then build (guard OR operator) AND NOT fault and compare: why would that be a dangerous interlock?
What the interactive shows, in words
The logic lab lets you connect AND, OR and NOT gates to switches and an output lamp. For guard AND operator AND NOT fault, only one of the 8 input combinations (guard on, operator on, fault off) lights the lamp. For (guard OR operator) AND NOT fault, three combinations light it, including guard off with operator on, which is unsafe.
Understand
The three operators
a and b is True only if both are True. a or b is True if at least one is True. not a flips True and False. Python works out not first, then and, then or, so not fault or guard means (not fault) or guard. Use brackets whenever you mix them.
A rule in one line
guard_closed = True
operator_present = True
fault = False
can_run = guard_closed and operator_present and not fault
print(can_run) # TrueThe variable name says what True means. Test all 8 combinations: can_run must be True in exactly one of them.
Ranges and short-circuits
0 <= temp_c <= 45 is Python's chained comparison: the same as 0 <= temp_c and temp_c <= 45. Python also short-circuits: in a and b, if a is False it never looks at b. That lets you write count > 0 and total / count > 50 without dividing by zero.
Explain it another way: intuitive
and is a door with several locks: every key must turn. or is a room with several doors: any one will do. not swaps yes and no.
Explain it another way: technical
Python's Boolean operators return one of their operands and evaluate lazily. Precedence is not > and > or, all lower than comparisons, so x > 0 and y > 0 needs no brackets.
Explain it another way: mathematical
In Boolean algebra, AND is multiplication and OR is addition (with 1 + 1 = 1). De Morgan's laws: not (a and b) = (not a) or (not b); not (a or b) = (not a) and (not b).
Explain it another way: applied
Industrial machine guards combine several sensors in exactly this way, and safety standards require showing what happens for every combination, including a sensor that fails.
Try these examples
Example 1
Rule: 'The vent opens if it is hotter than 28 °C, or the humidity is above 85 % while it is not raining.' Write it.
The worked solution is in the online lesson.
Common mix-ups
'or' means 'one or the other but not both'.
✓ Python's or is True when either or both are True. 'One but not both' is exclusive or, written a != b for bools.x == 1 or 2 checks whether x is 1 or 2.
✓ It means (x == 1) or 2, which is always truthy. Write x == 1 or x == 2.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. guard, operator and fault are each True or False (8 combinations). For how many of the 8 combinations is this Python condition True: guard or operator?
Answer: rows
2. Which condition is True exactly when temp_c is from 0 to 45 inclusive?
- 0 < temp_c < 45
- 0 <= temp_c <= 45
- temp_c >= 0 or temp_c <= 45
3. Why is (guard or operator) and not fault a dangerous interlock?
- It is too strict
- The press can run with the guard open if an operator is present
- It ignores faults
4. How does Python read not fault and guard or override?
- not (fault and guard or override)
- ((not fault) and guard) or override
- not fault and (guard or override)
5. Why does count > 0 and total / count > 50 never divide by zero?
- Python checks the right side first
- If count > 0 is False, Python never evaluates the division
- Division by zero gives 0 in Python
Apply it
Write the interlock for a laser cutter: it may fire only if the lid is closed, the extractor fan is on, the temperature is from 5 °C to 40 °C and no emergency stop is pressed. Write it as one expression, then print a table of a few important combinations and check each.
Reflect
When a machine has a safety rule, why test every combination rather than just the usual ones?
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?
Why it matters
Off-by-one and < versus <= mistakes are among the most common bugs in control code, and they only show up at exactly the boundary. Typical values never find them. Boundary testing is cheap, systematic and catches them every time.
Goals
- Choose test values on, just below and just above each boundary.
- Use a specification, not the code, to decide what each test should expect.
- Find a < versus <= bug with boundary tests and fix it.
Predict
Version C uses elif temp_c < 45. The specification allows charging up to and including 45 °C. Which test reveals the bug?
- 20 °C
- 45 °C
- 60 °C
Write down your guess and your reason. The reveal is in the online lesson.
Discover
For each version, first add a few typical tests (10, 20, 30 °C). Do they find any bug? Then press 'Add the boundary tests' and record which version fails where. Which single version matches the specification?
What the interactive shows, in words
The boundary tester keeps a table of test temperatures with the specification's answer, the selected version's answer and pass or fail. Adding the boundary tests (−0.5, 0, 0.5, 44.5, 45, 45.5) shows: Version A fails only at 0; Version B passes all; Version C fails only at 45. Typical values such as 20 °C pass for all three versions.
Understand
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")
Explain it another way: intuitive
If a fence is supposed to stop at the edge of the garden, you check right at the edge, not in the middle of the lawn.
Explain it another way: technical
Boundary value analysis partitions the input into ranges that should behave alike (equivalence classes) and tests at and around each partition edge, where off-by-one and comparison-operator faults concentrate.
Explain it another way: applied
Thermal cut-outs, over-current trips and speed limits are all thresholds. Certification testing of real products checks behaviour at each specified limit, for exactly this reason.
Try these examples
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.
The worked solution is in the online lesson.
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.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A thermometer reports in steps of 0.5 °C. The alarm rule is if temp_c >= 30: alarm(). As the temperature rises from 28 °C one step at a time, what is the first reading that sets off the alarm, in °C?
Answer: °C
2. 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
3. Where should a test's expected value come from?
- From running the code
- From the specification, worked out by hand
- From guessing
4. Version A uses if temp_c <= 0: return 'BLOCK: too cold'. Which input reveals its bug?
- -5
- 0
- 20
5. A rule has three thresholds. Using on, just-below and just-above tests for each, how many boundary tests is that?
Answer: tests
Apply it
Write boundary asserts for your tank classify(level_pct) function from the if/elif lesson (LOW below 20 %, OK 20–90 %, HIGH above 90 %), in 0.5 % steps. Deliberately change one <= to <, run the tests, and record which assert catches it.
Reflect
Which boundary in a machine you use every day would you most want tested, and why?
Week 6: Loops
This week you will
- Loop over a list of readings to total, count and find extremes, guarding against an empty list.
- Flag implausible readings and explain why a mean alone can mislead.
- Repeat a calculation with while until a condition is met, and say when for or while is the better choice.
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 it matters
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.
Goals
- 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
Write down your guess and your reason. The reveal is in the online lesson.
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, in words
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'.
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.
Explain it another way: 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.
Explain it another way: mathematical
Mean x̄ = (1/n) Σ xᵢ. The loop computes Σ xᵢ incrementally: Sₖ = Sₖ₋₁ + xₖ, with S₀ = 0, then divides by n.
Explain it another way: 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.
Try these examples
Example 1
Readings 3.71, 3.69, 3.66, 3.62 V from a battery. Find the mean with a loop.
The worked solution is in the online lesson.
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 questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. 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: °C
2. How many times does the body of for r in readings: run if readings has 7 items?
- 6
- 7
- 8
3. What happens with total / len(readings) when readings is []?
- It gives 0
- ZeroDivisionError
- It gives None
4. In a loop that totals readings, where should print(total) go to print the total once?
- Indented inside the loop
- After the loop, not indented
- Before the loop
5. Readings 20, 22, 24 and 26 °C. What is the mean, in °C?
Answer: °C
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()?
Go further (online)
- Python tutorial: for statements
The official explanation of for loops and range().
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?
Why it matters
Summaries are only useful if they reveal problems. A loop that counts readings over a limit, tracks the extremes and flags impossible values turns a wall of numbers into a decision: fine, inspect, or replace the sensor.
Goals
- Combine a loop and an if to count readings that meet a condition.
- Find the maximum and minimum with a loop, starting from the first reading.
- Flag implausible readings (glitches) and explain why a mean alone can mislead.
Predict
Readings: 21.4, 21.6, −40.0, 21.9, 22.1, 85.0, 22.0 °C. What is the mean?
- About 21.8 °C
- Exactly 22.0 °C
- About 30 °C
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Open the Smart Greenhouse at Level 2 ('Read the data'). Find the glitch in the ten noisy readings and the mean without it. While you work, write the loop you are running in your head: what do you count, what do you compare, what do you skip?
What the interactive shows, in words
The Smart Greenhouse Level 2 task gives ten thermometer readings, one of them an obvious glitch, and asks for the mean without it. On paper: list the readings, cross out any outside a plausible band, add the rest and divide by how many remain. In this lesson's example, 21.4, 21.6, −40.0, 21.9, 22.1, 85.0, 22.0 has mean 22.0, max 85.0, min −40.0 and 2 glitches.
Understand
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.
Explain it another way: intuitive
The mean is like the average height of a class: it can't tell you that one person is on stilts and another is sitting on the floor.
Explain it another way: technical
Each pass may update several accumulators: counters, running extrema and flags. The extrema must be initialised from the data, not from a constant, to be correct for every input range.
Explain it another way: mathematical
The mean is sensitive to outliers: one value of 85 among six near 22 adds (85 − 22)/7 ≈ 9 °C to it. The minimum and maximum, and a count of out-of-band values, expose what the mean hides.
Explain it another way: applied
Industrial data pipelines run plausibility and range checks on every sensor channel before using the data, and raise a maintenance alert when the glitch count rises.
Try these examples
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?
The worked solution is in the online lesson.
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.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A loop runs if r > 55: over = over + 1 for each reading r in [62.7, 51.5, 58.6, 63.0, 54.8, 55.0] (°C), starting from over = 0. What is over at the end?
Answer: readings
2. To find the hottest reading in a loop, what should hottest start as?
- 0
- The first reading in the list
- 100
3. Why report the max, the min and a glitch count as well as the mean?
- To make the report longer
- Because a mean can look normal while impossible readings are hidden in it
- Because the mean is usually wrong
4. Readings 18.2, 25.6, 19.9 and 23.4 °C. What is the range, max − min, in °C?
Answer: °C
Apply it
Extend your log program: report the mean of only the plausible readings, the max and min, and the number of glitches. Finish the Smart Greenhouse Level 2 task and check your program gives the same mean without the glitch.
Reflect
What would you want a maintenance engineer to see first in your log report, and why?
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?
Why it matters
Sometimes you don't know how many steps a job takes: cool until safe, fill until full, retry until a reply arrives. A while loop keeps going until a condition stops being true, which is exactly how many simulations and controllers work.
Goals
- Use a while loop when the number of passes is not known in advance.
- Make sure something inside the loop moves it towards its stopping condition.
- Choose between for and while for a given engineering task.
Predict
excess = 60.0, and while excess > 5: excess = excess * 0.8. Roughly how many passes?
- About 3
- About 12
- It never stops
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, type the cooling program from this lesson and run it: do you get 12 minutes? Then change 0.8 to 0.9 (slower cooling) and predict before running. Finally, break it on purpose by deleting the multiply line, and add a safety limit so it still stops.
What the interactive shows, in words
In the Code Lab the cooling program prints '12 4.12': the excess temperature falls 60.0, 48.0, 38.4, 30.72, 24.58, 19.66, 15.73, 12.58, 10.07, 8.05, 6.44, 5.15, 4.12 °C, so the loop stops after 12 passes. With 0.9 instead of 0.8 it takes 24 passes.
Understand
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.
Explain it another way: intuitive
Stirring tea until the sugar has dissolved: you don't count stirs in advance, you check each time and stop when it's done.
Explain it another way: technical
while evaluates its condition before each iteration and exits on False. Termination needs a variant: a quantity that changes monotonically towards the exit condition, plus a hard iteration limit in safety-relevant code.
Explain it another way: mathematical
Excess after n minutes: E·kⁿ (here 60 × 0.8ⁿ). The loop finds the smallest n with 60 × 0.8ⁿ ≤ 5, i.e. 0.8ⁿ ≤ 1/12. Since 0.8¹¹ ≈ 0.086 > 0.083 and 0.8¹² ≈ 0.069, n = 12. This is a simplified cooling model with a fixed fraction lost per minute.
Explain it another way: applied
Simulations step time forward in a while loop until something happens: a tank fills, a robot reaches its goal, a temperature settles. The same pattern appears in retry loops for radio messages.
Try these examples
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?
The worked solution is in the online lesson.
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.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A motor is 75 °C hotter than the room. Each minute of cooling multiplies the difference by 0.5. The program runs: while excess > 5: excess = excess * 0.5; minutes = minutes + 1 (starting from excess = 75, minutes = 0). What is minutes when the loop ends?
Answer: min
2. 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
3. Which job suits a while loop best?
- Print each of 50 readings
- Keep heating until the water reaches 60 °C
- Add up the readings in a list
4. x = 2. How many times does while x > 5: x = x - 1 run?
- 0
- 1
- It never stops
Apply it
Simulate a phone charging: start at 12 % and add 7 % each 10-minute step while below 80 %. Print each step and the total time. Then add a guard so the loop also stops if the battery temperature (add 0.4 °C per step from 25 °C) exceeds 35 °C.
Reflect
What is the safety limit you would add to any while loop that controls real hardware, and why?
Week 7: Functions
This week you will
- Package a calculation as a function with parameters, a return value and a docstring stating units.
- Write assert-based tests with independently worked expected values and float tolerances.
- Decompose a data-processing program into small, separately tested functions.
Package a calculation as a function
A robot converts wheel rpm to speed in six places in its code. One of them has a bug. How do you fix all six at once?
Why it matters
A function gives a calculation a name, a clear list of inputs and one output. Write it once, check it once, and every part of the program that calls it gets the same correct answer. That is how large engineering programs stay trustworthy.
Goals
- Define a function with parameters and a return value, and call it with arguments.
- Explain the difference between returning a value and printing it.
- Write a docstring that states what the function does and the units of its inputs and output.
Predict
def double(x): print(x * 2). What is stored in y after y = double(5)?
- 10
- None
- An error
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose wheel_speed_m_per_s. Feed it 60 rpm and 0.1 m and work out the answer by hand first. Then compare versions A, B and C: which one matches your hand calculation? Run the tests to confirm.
What the interactive shows, in words
The function machine shows a Python function with a docstring, three versions of its body and a set of assert tests. For wheel_speed_m_per_s: version A (rpm / 60 * math.pi * diameter_m) passes all three tests; version B forgets to divide by 60 (60 rpm, 0.1 m gives 18.85 instead of 0.314 m/s); version C uses 2π with the diameter (0.628 m/s).
Understand
Define once, call many times
import math
def wheel_speed_m_per_s(rpm, diameter_m):
"""Ground speed of a wheel in m/s, from its rpm and diameter in metres."""
return rpm / 60 * math.pi * diameter_m
print(round(wheel_speed_m_per_s(120, 0.065), 3)) # 0.408def names the function, the brackets list its parameters, and return hands back the result.
Return, don't just print
A returned value can be stored, compared, tested or passed to another function: if wheel_speed_m_per_s(rpm, d) > 1.5: slow_down(). Printing inside a function only shows text and gives back None. Keep functions quiet; print at the top level of the program.
A docstring is a promise
The triple-quoted line under def is a docstring. It says what the function does and the units of its inputs and output. Anyone using the function should be able to trust it without reading the body, and tests (next lesson) check that the promise is kept.
Explain it another way: intuitive
A function is a machine: put the inputs in the hopper, it does the same job every time, and one answer comes out of the chute.
Explain it another way: technical
Calling a function binds each parameter to an argument in a new local scope, runs the body, and evaluates to the returned object (None if there is no return). Local variables disappear when the call ends.
Explain it another way: mathematical
v = (n/60)·π·d: n/60 turns per second times the circumference π·d metres per turn. Units: (1/s) × m = m/s. 120 rpm with a 65 mm wheel gives 2 × π × 0.065 ≈ 0.408 m/s.
Explain it another way: applied
Robot firmware has functions like this for every conversion (encoder ticks to metres, ADC counts to volts). A unit-conversion fix in one function reaches everywhere at once.
Try these examples
Example 1
Write mean(values) that returns the mean of a non-empty list, and use it for [41.2, 42.0, 43.5].
The worked solution is in the online lesson.
Common mix-ups
A function that prints its answer has returned it.
✓ Printing shows text; only return gives the caller a value.Parameters must have the same names as the variables you pass in.
✓ Arguments are matched by position (or by name=value). The names inside and outside can differ.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. def wheel_speed_m_per_s(rpm, diameter_m): return rpm / 60 * math.pi * diameter_m. What does wheel_speed_m_per_s(150, 0.05) return, in m/s?
Answer: m/s
2. Why is return better than print inside a calculation function?
- return is faster to type
- The returned value can be used in further calculations and tests
- print does not work inside functions
3. def area_m2(width_m, height_m): return width_m * height_m. What does area_m2(3, 0.5) return?
- 1.5
- 3.5
- An error
4. def f(x): x * 2 (no return). What does f(4) give?
- 8
- None
- 4
5. Using v = rpm / 60 × π × d, what speed in m/s does a 0.2 m wheel at 30 rpm give, to 3 decimal places?
Answer: m/s
Apply it
Write rpm_for_speed(speed_m_per_s, diameter_m), the inverse of wheel_speed_m_per_s, with a docstring. Check that wheel_speed_m_per_s(rpm_for_speed(0.5, 0.065), 0.065) gives 0.5 (within a tolerance).
Reflect
Which calculation from earlier this term would you turn into a function first, and why?
Go further (online)
- Python tutorial: defining functions
The official guide to def, parameters, return and docstrings.
Promises and proof: tests with assert
Three versions of a °C-to-°F function all run without errors. Only one is right. How can three lines of tests tell them apart instantly?
Why it matters
A function's docstring is a promise; a test is the proof. Tests take seconds to write and run every time the code changes, so a bug introduced next month is caught before it reaches a machine.
Goals
- Write assert-based tests whose expected values are worked out independently.
- Compare float results within a tolerance in tests.
- Choose test inputs that cover typical, special and boundary cases.
Predict
Which single test input best separates a correct °C-to-°F function from (c + 32) * 9 / 5?
- Any input: they always differ
- 0 °C (should give 32 °F)
- There is no way to tell
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose c_to_f and run the tests on versions A, B and C. Then choose led_resistor_ohm: version B is correct, but why would assert led_resistor_ohm(3.3, 2.0, 10) == 130 fail for it? Look at the value it actually returns.
What the interactive shows, in words
The function machine's c_to_f has three versions: A, c * 9 / (5 + 32), gives 0.0 at 0 °C; B, (c + 32) * 9 / 5, gives 57.6; C, c * 9 / 5 + 32, gives 32.0 and passes all tests (0 → 32, 100 → 212, −40 → −40). For led_resistor_ohm, version B returns 129.99999999999997 for (3.3, 2.0, 10), so its tests compare within 1e-9.
Understand
A test is an assert
def c_to_f(c):
"""Convert a temperature in °C to °F."""
return c * 9 / 5 + 32
assert c_to_f(0) == 32
assert c_to_f(100) == 212
assert c_to_f(-40) == -40
print("all tests passed")assert condition does nothing if the condition is True and stops with AssertionError if it is False.
Expected values must be independent
Work out each expected value from somewhere other than the code: a reference point (water freezes at 0 °C = 32 °F), a hand calculation or a datasheet. If you copy the function's own output into the test, the test will happily confirm a bug.
Floats need a tolerance
(3.3 - 2.0) / 0.01 is 129.99999999999997, so == 130 fails even though the function is right. Write assert abs(led_resistor_ohm(3.3, 2.0, 10) - 130) < 1e-9, or math.isclose(...). Pick a tolerance that makes physical sense for the quantity.
Explain it another way: intuitive
A test is like checking a new kitchen scale with a 1 kg bag of sugar: you already know the right answer, so the scale has to match it.
Explain it another way: technical
assert raises AssertionError when its expression is falsy. Unit tests pin a function's contract at chosen points: typical inputs, special values and boundaries. Frameworks such as pytest collect and run them automatically.
Explain it another way: applied
Engineering software teams run thousands of tests automatically on every change. A failing test blocks the change until someone fixes the code or proves the test wrong.
Try these examples
Example 1
Write tests for current_ma(v, r_ohm), which returns the current in mA.
The worked solution is in the online lesson.
Common mix-ups
If code runs without an error, it is correct.
✓ Running proves only that it does not crash. Tests against known answers show whether it is right.A failing test always means the function is wrong.
✓ Sometimes the test is wrong, for example by comparing floats with ==. Check both.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. You are testing def current_ma(v, r_ohm): return v / r_ohm * 1000. To write assert abs(current_ma(9, 100) - EXPECTED) < 0.01, work EXPECTED out by hand with Ohm's law. What is it, in mA?
Answer: mA
2. A correct function returns 129.99999999999997 for an expected 130. Which test is right?
- assert result == 130
- assert abs(result - 130) < 1e-9
- assert int(result) == 130
3. Why shouldn't you run the function and paste its output into the test as the expected value?
- It is slower
- The test would then agree with any bug the function has
- assert cannot use numbers
4. Which set of inputs best tests c_to_f?
- 1, 2, 3
- 0, 100, −40
- 100, 100, 100
Apply it
Write three tests for your rpm_for_speed function and three for the wheel speed function, with expected values worked out by hand. Break each function on purpose (change 60 to 6) and check a test catches it.
Reflect
What is one function from this term you would not trust until it had tests, and which inputs would you test it with?
Decompose a program into functions
Raw ADC counts in, a temperature report out. Should that be one long block of code, or three small functions?
Why it matters
Real sensor software is a pipeline: convert raw counts, apply calibration, check plausibility, summarise, decide. Each stage as a small, tested function means you can find a bug in minutes and reuse a stage for the next sensor.
Goals
- Split a data-processing program into small functions that each do one job.
- Chain functions so the output of one is the input of the next.
- Test each function on its own before testing the whole program.
Predict
to_celsius(to_volts(232)): which function runs first?
- to_celsius
- to_volts
- Both at the same time
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, type the three-function pipeline from this lesson. Run it and check the report. Then test each function on its own: to_volts(1023) should be 3.3 and to_celsius(0.75) should be 25.0 (within a tolerance). Finally, add a fourth function count_over(values, limit_c).
What the interactive shows, in words
The Code Lab exercise can be done by hand: for raw counts 228, 231, 235 and 240, volts = raw × 3.3 / 1023 and temperature = (volts − 0.5) × 100 give about 23.5, 24.5, 25.8 and 27.4 °C, so the report reads 'mean 25.3 °C, range 23.5 to 27.4 °C'.
Understand
Three small functions
def to_volts(raw):
"""10-bit ADC count (0–1023) to volts, 3.3 V reference."""
return raw * 3.3 / 1023
def to_celsius(volts):
"""TMP36-style sensor: 10 mV per °C, 0.5 V at 0 °C."""
return (volts - 0.5) * 100
def summarise(values):
"""Return (mean, minimum, maximum) of a non-empty list."""
return sum(values) / len(values), min(values), max(values)Chain them in the main program
raw_counts = [228, 231, 235, 240]
temps_c = []
for raw in raw_counts:
temps_c.append(to_celsius(to_volts(raw)))
mean_c, low_c, high_c = summarise(temps_c)
print(f"mean {mean_c:.1f} °C, range {low_c:.1f} to {high_c:.1f} °C")Run after the three functions above, it prints mean 25.3 °C, range 23.5 to 27.4 °C.
One job per function
If you can't describe a function in one sentence without 'and', split it. Small functions are easy to test (to_volts(0) is 0.0, to_volts(1023) is 3.3), easy to reuse (the same to_volts serves a light sensor) and easy to replace (a new sensor needs only a new to_celsius).
Explain it another way: intuitive
Like a production line with separate stations: cutting, drilling, painting. If the paint is wrong, you check the painting station, not the whole factory.
Explain it another way: technical
Decomposition into pure functions (output depends only on inputs, no side effects) makes each unit independently testable and composable: f(g(x)). The main program becomes a short, readable description of the pipeline.
Explain it another way: mathematical
V = raw × 3.3/1023 and T = (V − 0.5) × 100 compose into T = (raw × 3.3/1023 − 0.5) × 100. For raw = 232: V ≈ 0.748 V and T ≈ 24.8 °C. Each count is about 3.2 mV, about 0.32 °C: the sensor's resolution.
Explain it another way: applied
Embedded and data teams structure sensor code exactly like this, often in separate files, so a calibration change touches one small, tested function.
Try these examples
Example 1
The sensor is re-calibrated: it reads 0.3 °C too high. Where does the fix go?
The worked solution is in the online lesson.
Common mix-ups
Splitting code into functions makes it slower and longer, so it is worse.
✓ The tiny cost is repaid many times over in clarity, testing and reuse.A function should print its result so you can see it.
✓ Return it. Print only in the main program, so the function stays reusable and testable.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A 10-bit ADC reads raw = 307. to_volts(raw) returns raw * 3.3 / 1023, and to_celsius(v) returns (v - 0.5) * 100 (a TMP36-style sensor: 10 mV per °C with a 0.5 V offset). What is to_celsius(to_volts(307)), in °C?
Answer: °C
2. Which function does one job?
- read_convert_check_and_print(path)
- to_volts(raw)
- do_everything()
3. Why test to_volts and to_celsius separately before the whole pipeline?
- It is required by Python
- If the whole report is wrong, you already know which stages are right
- Separate tests run faster
4. With volts = raw × 3.3 / 1023, how many millivolts is one ADC count, to 2 decimal places?
Answer: mV
Apply it
Add plausible(temp_c) (True from −40 to 125 °C) and count_over(values, limit_c) to the pipeline, each with a docstring and two asserts. Then rewrite your main program so it reads like a short list of steps.
Reflect
How did splitting the program change how confident you are that it is right?
Week 8: Debugging
This week you will
- Read a traceback from the bottom up and locate the line and kind of error.
- Use a reproduce–hypothesise–test method with print probes to find a logic bug.
- Validate input with try / except and plausibility checks, counting what is rejected.
Read the traceback
Your program crashes with six lines of red text. Most people read the top. Why does the answer start at the bottom?
Why it matters
Error messages are not insults; they are the most useful debugging information you will ever get for free. Engineers who read them calmly fix crashes in seconds instead of hours.
Goals
- Read a traceback from the bottom up to find the error type, message and line.
- Tell syntax errors, runtime errors and logic errors apart.
- Name the usual cause of NameError, TypeError, ValueError, ZeroDivisionError and IndexError.
Predict
A traceback ends with ZeroDivisionError: division by zero, and the line above says line 5, in mean. Where is the fault?
- Line 1 of the program
- Line 5, inside the function mean
- In Python itself
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Work through 'Text plus a number', 'Mean of an empty log' and 'One equals sign'. For each, read the traceback from the bottom, pick the line you suspect and check. Use the print probe to see the variables just before the crash.
What the interactive shows, in words
The bug hunt shows a short program, what was expected and what actually happened. 'Text plus a number' crashes on line 3 with TypeError: can only concatenate str (not "float") to str. 'Mean of an empty log' crashes on line 5 inside mean, called from line 7, with ZeroDivisionError. 'One equals sign' fails before running with a SyntaxError on line 3, suggesting '=='. Selecting a line and checking explains the cause and the fix.
Understand
Bottom up
Traceback (most recent call last):
File "log.py", line 7, in <module>
print(mean([]))
File "log.py", line 5, in mean
return total / len(readings)
ZeroDivisionError: division by zeroLast line: the error type and message. Just above: the file, line and code where it happened. Higher up: the chain of calls that got there (line 7 called mean).
Three kinds of error
Syntax errors stop the program before anything runs: if x = 5: (Python even suggests ==). Runtime errors crash it part-way: dividing by zero, adding text to a number. Logic errors never crash: the program runs and gives a wrong answer. Logic errors are the hardest, so tests matter.
The usual suspects
NameError: a misspelt name or one used before it is assigned. TypeError: the wrong type, such as "23.5" + 0.4. ValueError: right type, bad value, such as float("ERR"). ZeroDivisionError: dividing by zero, often an empty list. IndexError: a list position that does not exist, such as readings[7] in a 7-item list.
Explain it another way: intuitive
A traceback is a trail of footprints. The crash is at the end of the trail; earlier footprints show how you got there.
Explain it another way: technical
When an exception is not handled, Python unwinds the call stack and prints each frame, oldest first, then the exception type and message. Python 3.11 and later also underline the exact part of the line that failed.
Explain it another way: applied
On robots and servers, tracebacks are written to log files. The first thing an engineer does after a failure is find the last traceback in the log and read it from the bottom.
Try these examples
Example 1
A traceback ends: IndexError: list index out of range, at line 4: last = readings[len(readings)]. Explain and fix.
The worked solution is in the online lesson.
Common mix-ups
The first line of a traceback is the most important.
✓ The last line names the error, and the line above it shows where. Read from the bottom.No error message means no bug.
✓ Logic errors give wrong answers silently. Only tests and checks reveal them.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. Which part of a traceback tells you the kind of error?
- The first line, 'Traceback (most recent call last)'
- The last line
- The middle line
2. Which is a logic error?
- if x = 5:
- print(10 / 0)
- A mean computed as total / (count + 1)
3. float("ERR") raises which error?
- TypeError
- ValueError
- NameError
4. A list has 7 readings. What is the largest valid index?
Answer:
Apply it
Write five tiny programs, each causing one of NameError, TypeError, ValueError, ZeroDivisionError and IndexError. Run each and copy its last traceback line into a table with one sentence on the cause and the fix.
Reflect
Which error message did you find hardest to understand, and what does it actually mean now?
Go further (online)
- Python tutorial: errors and exceptions
Official explanations of syntax errors, exceptions and tracebacks.
Reproduce, hypothesise, test: hunting logic bugs
A robot's speed log says 240 m/s. Nothing crashed. Where do you even start?
Why it matters
Logic bugs give wrong answers quietly. Guessing and changing things at random wastes hours and adds new bugs. A scientific method, applied to code, finds the cause reliably, and the test you write afterwards stops it coming back.
Goals
- Apply a systematic method: reproduce, hypothesise, test, fix, keep the test.
- Use print probes to check a hypothesis about where values first go wrong.
- Find and fix off-by-one, indentation and unit-mismatch bugs.
Predict
readings = [20.5, 21.0, 22.5, 24.0] but a loop uses range(1, len(readings)) and divides by len(readings). What does it print?
- 22.0
- 16.875
- An IndexError
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Work through 'Mean too low', 'Count stuck at 0' and 'A very fast robot'. For each: state a hypothesis in one sentence, place a print probe to test it, then pick the faulty line. Write down the probe that convinced you.
What the interactive shows, in words
In the bug hunt, 'Mean too low' prints mean: 16.875 instead of 22.0; a probe after line 3 shows i taking 1, 2, 3, never 0, so line 3's range(1, ...) is the bug. 'Count stuck at 0' prints 0 instead of 3; a probe shows line 6 runs once with r = 48, because return is inside the loop. 'A very fast robot' prints [240.0, 260.0, 240.0] m/s for distances in millimetres; the speeds are really 0.24–0.26 m/s.
Understand
The method
- Reproduce: find a small input that always shows the bug. 2. Hypothesise: 'I think the first reading is never added.' 3. Test the hypothesis: add a print, or try an even smaller input. 4. Fix the cause, not the symptom. 5. Keep a test that would have caught it.
Print probes
A print just after a suspect line shows the values at that moment: print("i", i, "total", total) inside a loop. If i starts at 1, the hypothesis is confirmed. Remove or comment out probes once the bug is fixed; keep the assert you add.
Three classic logic bugs
Off-by-one: range(1, n) skips index 0; range(n + 1) runs one too far. Indentation: a return inside a for loop returns after the first item. Units: millimetres divided by seconds labelled m/s is 1000 times too big. The first two show in a probe of the loop; the third shows in a units check.
Explain it another way: intuitive
Like finding which bulb has failed in a string of fairy lights: you test halfway along, then halfway again, rather than replacing bulbs at random.
Explain it another way: technical
Debugging is hypothesis testing. Each probe or reduced input should split the possible causes. Fixing without a confirmed cause risks masking the bug; a regression test prevents it returning.
Explain it another way: applied
Engineering teams write a short bug report for every serious fault (symptom, cause, fix, test). The project brief this term asks for exactly that, because it shows how you think.
Try these examples
Example 1
count_over([48, 52, 55, 49, 61], 50) returns 0 instead of 3. Find the bug.
The worked solution is in the online lesson.
Common mix-ups
Debugging means changing things until it works.
✓ Debugging means forming and testing hypotheses until you know the cause, then fixing that cause.Once it's fixed, the bug is gone for good.
✓ Bugs come back when code changes. A test that would have caught it keeps it gone.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. readings = [15.0, 22.9, 29.8, 29.6, 19.2]. The buggy code sets total = 0, runs for i in range(1, len(readings)): total = total + readings[i], then calls print(total / len(readings)). What does it print (to 2 decimal places)?
Answer:
2. A program gives a wrong total. What is the best first step?
- Rewrite the whole program
- Find a small input that always shows the wrong total
- Change the < signs to <= and see
3. A function returns after checking only the first reading. What is the most likely cause?
- A misspelt variable
- return is indented inside the for loop
- The list is empty
4. distance_mm differences divided by interval_s are printed as m/s and look 1000 times too big. Best fix?
- Divide the result by 1000 to convert mm/s to m/s
- Multiply by 1000
- Remove the label
Apply it
Take any program you wrote this term, plant a bug in it (or ask a friend to), and find it using the method. Write a four-line bug report: symptom, hypothesis, test that confirmed it, fix. Add the assert that would have caught it.
Reflect
Describe a time you fixed something by guessing. How would the method have changed what you did?
Catch bad data before it bites
A data logger writes ERR whenever its sensor hiccups. Should your program crash, skip the line, or quietly count it as zero?
Why it matters
Real logs contain blank lines, error codes and impossible values. A program that crashes on the first one is useless; a program that silently turns them into zeros is dangerous. Defensive checks make software that keeps working and tells you the truth about its data.
Goals
- Use try / except ValueError to handle a line that cannot be converted to a number.
- Add range (plausibility) checks based on the sensor's rated range.
- Count and report rejected data rather than silently discarding it.
Predict
A log line is -999.0, a common 'no reading' code. What does float("-999.0") do?
- Raises a ValueError
- Returns -999.0
- Returns None
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, type parse_reading from this lesson and run it on the sample lines. Then add your own nasty lines (" 21.5 ", "21,5", "nan", "1e3") and predict what each does before running. Which ones slip through, and how would you stop them?
What the interactive shows, in words
The Code Lab exercise can be traced by hand. parse_reading returns the number for '21.5' and '22.1'; None for 'ERR' and '' (float fails); and None for '-999.0' (outside −40 to 125). So good = [21.5, 22.1] and 3 of 5 lines are rejected. ' 21.5 ' converts (float ignores surrounding spaces) and '21,5' fails.
Understand
Validate every line
def parse_reading(line):
"""Return the reading in °C, or None if the line is not a plausible reading."""
try:
value = float(line)
except ValueError:
return None
if value < -40 or value > 125:
return None
return value
lines = ["21.5", "ERR", "", "-999.0", "22.1"]
good = []
for line in lines:
value = parse_reading(line)
if value is not None:
good.append(value)
print(good) # [21.5, 22.1]Two different checks
The conversion check (try / except ValueError) catches lines that are not numbers at all: ERR, blanks, '--'. The plausibility check catches numbers that cannot be real: −999.0, 130.5. The band comes from the sensor's datasheet (here −40 to 125 °C, typical of small temperature sensors) or from physics.
Never hide the evidence
Count what you reject and report it: '3 of 480 lines rejected'. Never replace bad lines with 0, which drags the mean down and looks like a real reading. Catch only the error you expect (except ValueError), not every error, so genuine bugs still show up.
Explain it another way: intuitive
A bouncer at a door: first check it is a ticket at all, then check it is for tonight. People without one are turned away and counted, not let in as 'nobody'.
Explain it another way: technical
try / except handles a specific exception locally; the function's contract (return a float or None) is documented in the docstring. Validation at the boundary keeps the rest of the program working on clean, typed data.
Explain it another way: applied
Industrial and scientific data pipelines always have this stage, often called input validation or data cleaning, and keep counts of rejected records as a health signal for the sensors.
Try these examples
Common mix-ups
If float() succeeds, the reading is good.
✓ −999.0 and 130.5 convert fine but are impossible. Range checks are also needed.Catching every exception makes a program robust.
✓ It makes bugs invisible. Catch the specific errors you expect and handle them deliberately.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A log has the lines ["-999.0","25.8","-999.0","21.4","21.6","19.1","20.0","--"]. The program keeps a line only if float(line) works and -40 <= value <= 125 (the sensor's rated range, °C); otherwise it skips it. How many readings are kept?
Answer: readings
2. Which check rejects the line "130.5" from a sensor rated −40 to 125 °C?
- The conversion check (float fails)
- The plausibility (range) check
- Neither
3. Why is replacing bad lines with 0 a bad idea?
- 0 takes more memory
- 0 looks like a real reading and drags the mean down
- Python cannot store 0
4. Why write except ValueError rather than a bare except?
- It runs faster
- A bare except would also hide real bugs, such as a misspelt name
- Bare except is not allowed
Apply it
Extend parse_reading to reject nan, then write four asserts (a good line, ERR, blank and −999.0). Use it in your log program and print how many lines were rejected out of the total.
Reflect
What would you want to happen if 30 % of a log's lines were rejected? Should the program still report a mean?
Go further (online)
- Python tutorial: handling exceptions
The official guide to try and except.
Week 9: Programming project
This week you will
- Plan, write and test a small program that processes a log of sensor readings and reports a decision.
- Explain the program's structure, its tests and one bug found and fixed.
Plan the sensor-log checker
You have one day's temperature log from a machine and one question: does it need an inspection? What is your plan before you type a line?
Why it matters
The term project brings everything together: precise steps, types, formulas, decisions, loops, functions, tests and debugging. Engineers spend real time planning before coding, because a clear plan makes the code short and the testing obvious.
Goals
- Turn a project brief into precise requirements and an ordered algorithm.
- Decompose the program into functions with clear inputs, outputs and docstrings.
- Design a test log that exercises every branch, including malformed and boundary lines.
Predict
The brief says 'flag the machine if it gets too hot'. What should you do first?
- Start coding and decide later
- Turn it into a measurable rule, such as 'INSPECT if any reading is outside 10–60 °C or more than 2 lines are malformed'
- Ask Python to decide what 'too hot' means
Write down your guess and your reason. The reveal is in the online lesson.
Discover
Choose 'Sensor-log checker'. Order the six steps and mark the vague ones, then compare with the precise versions. Use the result as the skeleton of your plan: one function for each step that does real work.
What the interactive shows, in words
The step orderer's 'Sensor-log checker' lists six steps to order: open the log and read it a line at a time; skip and count lines that do not convert; add good readings to a list; compute mean, minimum and maximum; count readings outside 10–60 °C; report INSPECT if any are outside or more than 2 lines were malformed, otherwise OK. Two steps start vague ('Skip the bad lines', 'Flag the machine if it seems too hot').
Understand
From brief to requirements
The brief: read a temperature log, flag readings outside a safe band, report the mean, minimum and maximum, and decide whether the machine needs inspection. Requirements: safe band 10–60 °C inclusive; a line that won't convert is malformed and counted; report INSPECT if any reading is outside the band or more than 2 lines are malformed, otherwise OK; an empty log reports 'no readings' and INSPECT.
Decompose into functions
parse_reading(line) → float or None. summarise(values) → (mean, min, max). count_outside(values, low_c, high_c) → int. decide(values, malformed) → "INSPECT" or "OK". A short main program reads the lines, calls these and prints the report. Write a one-sentence docstring for each before writing its body.
Design the test log to break it
Include: normal readings; exactly 10.0 and 60.0 (safe); 9.9 and 60.1 (outside); ERR, a blank and −999.0; exactly 2 and then 3 malformed lines; and an empty log. Write the expected report for each test log by hand, from the requirements, before running anything.
Explain it another way: intuitive
Planning is drawing the map before the journey. It's quicker to fix a wrong turn on the map than halfway up the wrong mountain.
Explain it another way: technical
Requirements define observable behaviour; the decomposition defines interfaces (function signatures and contracts); the test plan defines how each requirement is verified, including equivalence classes and boundaries.
Explain it another way: applied
Condition-monitoring tools in factories implement this logic at scale: thresholds from the equipment manufacturer, data-quality counts and a simple, auditable decision rule.
Try these examples
Example 1
Test log: 25.0, 10.0, 60.0, ERR, ERR. What report should the checker give?
The worked solution is in the online lesson.
Common mix-ups
Planning is wasted time; real engineers just code.
✓ A few minutes of planning saves hours of rework, and the plan becomes your test list and your report.Test data should be realistic, so normal readings are enough.
✓ Test data should be designed to break the program: boundaries, malformed lines, empty logs.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. The safe band is 15–45 °C inclusive. Readings (°C): 44, 33, 28, 29, 20, 23, 49, 49, 24, 12, 33, 24. What percentage of the readings are outside the band?
Answer: %
2. Which test log best checks the safe-band boundary?
- 20.0, 30.0, 40.0
- 10.0, 60.0, 9.9, 60.1
- 100.0, 200.0
3. What should the checker do with an empty log?
- Crash with ZeroDivisionError
- Report 'no readings' and INSPECT
- Report a mean of 0 °C and OK
4. Why write each function's docstring before its body?
- Python requires it
- It fixes what the function promises, which tells you what to code and test
- It makes the program run faster
Apply it
Write your project plan: the requirements (with numbers), the four function signatures with docstrings, a flowchart or numbered algorithm for the main program, and at least three test logs with their expected reports worked out by hand.
Reflect
Which requirement in the brief was the most ambiguous, and how did you make it precise?
Go further (online)
- Academy: files and CSV data
How to read a log file line by line when you work on your own computer.
Build it, test it, break it
Your checker says OK for the real log. Will it still say the right thing when the logger glitches, the file is empty, or a reading is exactly 60.0?
Why it matters
Building in small, tested steps is how engineers keep a growing program under control. Each function you finish and test becomes something you can trust, so when the whole program misbehaves you know where not to look.
Goals
- Implement the planned functions one at a time, testing each with assert before moving on.
- Run the whole program on designed test logs and compare with hand-worked expected reports.
- Record one real bug found during testing: symptom, hypothesis, test and fix.
Predict
Lines "41.2", "ERR", "54.0", "--". What mean should the checker report?
- 23.8 °C (dividing by all 4 lines)
- 47.6 °C (dividing by the 2 good readings)
- It should crash
Write down your guess and your reason. The reveal is in the online lesson.
Discover
In the Code Lab, start with decide() from this lesson and its four asserts: run them. Then add parse_reading, summarise and count_outside one at a time, each with its own asserts, and only then the main program. Paste each of your test logs into the lines list and compare with your expected reports.
What the interactive shows, in words
The Code Lab exercise starts with decide(values, malformed): it returns INSPECT for an empty list, for any value below 10 or above 60, or when more than 2 lines are malformed; otherwise OK. Its tests: [20.0, 30.0] with 0 malformed → OK; [20.0, 61.0] → INSPECT; [10, 60] with 2 malformed → OK; [25.0] with 3 malformed → INSPECT; [] → INSPECT.
Understand
Build one function at a time
SAFE_LOW_C = 10
SAFE_HIGH_C = 60
def decide(values, malformed):
"""Return "INSPECT" or "OK" following the brief."""
if len(values) == 0:
return "INSPECT"
outside = 0
for v in values:
if v < SAFE_LOW_C or v > SAFE_HIGH_C:
outside += 1
if outside > 0 or malformed > 2:
return "INSPECT"
return "OK"
assert decide([20.0, 30.0], 0) == "OK"
assert decide([20.0, 61.0], 0) == "INSPECT"
assert decide([10, 60], 2) == "OK" # band edges are safe
assert decide([25.0], 3) == "INSPECT"
assert decide([], 0) == "INSPECT"Reading the log
In the Code Lab, paste the log into a list: lines = ["41.2", "ERR", ...]. On your own computer, read a file instead:
with open("motor_log.txt") as f:
lines = f.read().splitlines()Either way the rest of the program receives the same list of strings, which is why parsing lives in its own function.
Keep a bug diary
When a test fails, don't just fix it: write the symptom (decide([10, 60], 2) said INSPECT), the hypothesis (< versus <= on the band), the test that confirmed it (a probe showed outside = 2) and the fix. This record is a deliverable of the project, and the habit is worth more than the program.
Explain it another way: intuitive
Like building a wall one course of bricks at a time and checking it with a level each time, instead of building the whole wall and hoping it's straight.
Explain it another way: technical
Incremental development with unit tests: each function is verified against its contract before integration. Integration tests (whole test logs with expected reports) then check that the pieces fit together.
Explain it another way: applied
This is how professional software is built: small changes, each covered by tests, run automatically. Your sensor-log checker is a miniature of real condition-monitoring software.
Try these examples
Example 1
A tester's log is 60.0, 60.0, 60.1. What should the report be?
The worked solution is in the online lesson.
Common mix-ups
If the program works on the real log, it's finished.
✓ It's finished when it gives the right report for every designed test log, including the ones built to break it.Tests slow you down.
✓ Tests make you faster: every later change is checked in seconds instead of by hand.
Practice questions
Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.
1. A motor log has the lines ["40.0","","50.6","n/a","","59.7","59.4","45.6","52.3"] (°C). The checker skips any line that float() cannot convert and averages the rest. What mean does it report, in °C?
Answer: °C
2. In what order should you build the checker?
- The whole program, then test it
- One function at a time, each with asserts, then the main program
- The tests last, if there is time
3. decide([10, 60], 0) returns INSPECT. Which line is most likely wrong?
- if outside > 0 or malformed > 2:
- if v < SAFE_LOW_C or v > SAFE_HIGH_C: written as <= and >=
- return "OK"
4. Which is the best bug-diary entry?
- Fixed a bug.
- decide([10, 60], 0) gave INSPECT. Hypothesis: edges treated as outside. A probe showed outside = 2. Fixed <= to <. Added assert.
- Changed some signs until it passed.
Apply it
Complete the project: the full checker with at least four tested functions, your test logs with expected and actual reports, a bug-diary entry for a real bug, and a one-page note explaining the algorithm so another learner can run it from the note alone.
Reflect
Which test log found the most interesting bug, and what did it teach you about your own code?
Go further (online)
- The Python Tutorial (official)
The official, free introduction to Python, written by its developers.