Textbooks/Engineering Programming With Python/Chapter 1Lite (plain text) version
1Algorithms before code
Version 1 · Technically checked (automated checks only) · 4 source lessons · 8 practice items
Introduction
The hardest part of a program is usually done before typing. Break the machine's job into steps a computer could follow, draw the decisions and loops as a flowchart, and list every combination of inputs in a rule table so no case is forgotten. Then write the first small program, a battery run-time calculator, and watch Python follow your steps exactly, including the wrong ones.
Explanation
This chapter is built from 4 School lessons. Each part below is the lesson's own explanation; open the lesson for its predict-and-discover activities.
1.1 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?
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.
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.
1.2 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?
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.
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.
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.
Open the full lesson: Flowcharts: drawing decisions and loops →
1.3 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?
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.
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.
1.4 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?
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.
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.
Open the full lesson: Your first Python program: battery runtime →
Worked examples
Break a machine's job into steps: example 1
Decompose 'keep the vaccine fridge between 2 °C and 8 °C' and write the decide step precisely.
Solution
Pieces: read the temperature every minute; decide; switch the compressor; log and alarm. Decide step: If the temperature is above 6 °C, switch the compressor on. If it is below 3 °C, switch it off. If it is outside 2–8 °C for 5 minutes in a row, sound the alarm. Each line names a number, a unit and an action.
Flowcharts: drawing decisions and loops: example 1
Start 40 L, add 25 L per pass, loop while level < 120. Trace it.
Solution
40 (True) → 65 (True) → 90 (True) → 115 (True) → 140 (False, stop). The pump runs 4 times and the tank ends at 140 L. Check: (120 − 40) / 25 = 3.2 → rounded up = 4.
Trace every case with a rule table: 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?
Solution
Not metal (so not A), not large (so not B), so bin C. Tracing each rule in order gives one clear answer, so this row is defined. Do this for all 8 rows to prove the brief is complete.
Your first Python program: battery runtime: example 1
The node sleeps at 0.5 mA most of the time. What runtime does the program give for current_ma = 0.5?
Solution
hours = 2000 / 0.5 = 4000.0 h, about 4000 / 24 ≈ 167 days. Real batteries also slowly lose charge on their own, so the true figure would be lower: state that assumption next to the result.
Interactive figures
Interactive figure (online). Description: 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.
Interactive figure (online). Description: 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.
Laboratory
Everything runs in your browser. No kit, nothing mains-powered. Simulations are simplified educational models.
Studio
Code Lab
Write a program that prints a battery's run time in hours and days from its capacity and the device's current.
Open Code Lab →BUILD level
BUILD: Traffic system, level 1
Write the junction's rules as a rule table and check that every combination of sensor inputs has an action.
Open BUILD: Traffic system, level 1 →
Guided practice
Answers are checked on the server; wrong answers get a hint and another try. Signed in, solved items also count towards the source lesson.
- 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
- 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 %
- 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
- 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
- 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? (rows)
- 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
- 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.) (min)
- Which variable name is best for a current measured in milliamps?
- c
- current
- current_ma
Engineering applications
Safety interlocks
Machine guards, lift doors and kiln controllers are specified as rule tables first. Listing every combination of sensor states exposes the one nobody thought of, such as a door sensor failing open while the motor runs.
Planning saves debugging
Ten minutes spent ordering steps and drawing the loop often saves an hour of debugging. A flowchart that never reaches its stop box is a program that never ends.
Watch
Optional verified videos. Nothing loads from YouTube until you press play.
- What's an algorithm? - David J. Malan (TED-Ed)
- Intro to Algorithms: Crash Course Computer Science #13 (CrashCourse)
Chapter summary
- Decompose a job into small, exact steps with clear inputs, outputs and a stopping rule.
- Flowcharts show decisions as diamonds and loops as arrows that go back.
- n on/off inputs make 2^n cases; a rule table lists them all so none is missed.
- Python runs your steps literally, top to bottom; names and units belong in the code.
Glossary
- Variables and assignment
- An assignment such as speed = 2.5 makes the name speed refer to the value 2.5. The right-hand side is worked out first, then the name is attached to the result.
- Comparisons and Boolean expressions
- Comparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10.
- Truth table
- A truth table lists the output of a logic function for every possible combination of its inputs; n inputs need 2^n rows.
- Block diagram
- A block diagram shows a system as labelled boxes connected by arrows, each arrow naming what flows between them: power, a signal, data or a force.
Definitions from the Field Guide.
Project: A pump controller on paper and in Python
A tank has a low-level sensor, a high-level sensor and a pump. Decompose the controller's job, draw its flowchart, write the full rule table including impossible sensor combinations, and implement it as a Python function that you call for every row of the table.
Deliverables
- A flowchart with a clear stop or repeat
- A complete rule table with an action for every row
- The function and a printout of every case
Keep your work in your Engineering Journal; it stays private unless you choose to share it.
References
- Allen B. Downey (2015). Think Python: How to Think Like a Computer Scientist, 2nd edition. O'Reilly Media.
- John V. Guttag (2016). Introduction to Computation and Programming Using Python, 2nd edition. MIT Press.
Further reading from the source lessons
- The Python Tutorial (official) ↗The official, free introduction to Python, written by its developers.
Publication record
- Version
- 1
- Status
- Technically checked (automated checks only)
- Technical review
- Automated checks only, last run 2026-11-29. No human, educator or mentor review is claimed.src/content/textbooks/textbooks.test.ts: schema, every lesson, diagram, practice item, video, Field Guide entry, lab and reference resolves; figure numbers recomputed; no practice answers in client payloads.
- Written by
- Compiled and written by the Tactiverge team with AI assistance, from Tactiverge School lessons that were themselves written with AI assistance.
- Licence
- All rights reserved by the founders unless a licence is approved.
- Corrections
- None recorded yet.Spotted a mistake? Use “Report a problem” on any chapter, or see the corrections page.