TactivergeLite

Lite / Textbooks / Engineering Programming With Python / Chapter 1

1. Algorithms before code

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

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.

Figure 1.1. 3 inputs, 8 cases, check every one (described in words)

A rule table for three on/off inputs, hot, fan and door, listing all 8 combinations. The rule alarm = hot and not fan is true in 2 rows, which are highlighted: hot 1, fan 0, with door either 0 or 1.

Explanation

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

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

Open the Lite lesson: Break a machine's job into steps

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?
  1. The loop runs while level < target. Start level S, each pass adds A litres.

  2. After n passes the level is S + n·A. The loop stops at the first n where S + n·A ≥ target.

  3. Rearrange: n·A ≥ target − S, so n ≥ (target − S) / A.

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

  5. If S is already ≥ target, the condition is false at the first check and the pump runs 0 times.

Common mix-ups

Open the Lite 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

Open the Lite lesson: Trace every case with a rule table

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 minutes

What 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

Open the Lite 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, in words

Figure 1.2 from Break a machine's job into steps

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.

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.

Figure 1.3 from Flowcharts: drawing decisions and loops

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?

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.

The interactive versions are in the full chapter.

Laboratory

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

Practice

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

  1. Which step is too vague for a computer?
    Answer it in “Break a machine's job into steps”
  2. A step says 'Open the valve until moisture reaches 45 %'. What is the safest improvement?
    Answer it in “Break a machine's job into steps”
  3. In a flowchart, what does a diamond mean?
    Answer it in “Flowcharts: drawing decisions and loops”
  4. Why add 'or 20 passes have run' to the tank loop?
    Answer it in “Flowcharts: drawing decisions and loops”
  5. 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 it in “Trace every case with a rule table”
  6. A rule table for 3 yes/no sensors has only 7 rows. What is the risk?
    Answer it in “Trace every case with a rule table”
  7. 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 it in “Your first Python program: battery runtime”
  8. Which variable name is best for a current measured in milliamps?
    Answer it in “Your first Python program: battery runtime”

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)

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

Summary

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. Field Guide
Comparisons and Boolean expressions
Comparisons such as a < b give True or False; and, or and not combine them. Python allows chained comparisons like 0 <= x < 10. Field Guide
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. Field Guide
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. 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

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

References

Further reading from the lessons

← Contents2. Values, types and formulas →