Plan a program before you code it
Be able to break a problem down into steps and functions before coding.
Prerequisites
Intuition
Beginners start writing code straight away and get stuck. Experienced programmers plan first — often on paper.
The method:
- Write what the program should do in one sentence.
- Split it into 3–5 steps.
- For each step: what goes in, what comes out?
- Each step becomes a function.
- Code one step at a time and test it before the next one.
Then the fault is never more than one step away.
Code
The task: «A program that reads in exam results and shows how many passed.»
| Step | In | Out | Function |
|---|---|---|---|
| 1. Read the results | file name | list of numbers | read_results(file) |
| 2. Filter the passes | list, threshold | list of passes | passes(results, threshold) |
| 3. Count and show | list, total | text | summarise(passes, total) |
def read_results(file):
with open(file, encoding="utf-8") as f:
return [int(line.strip()) for line in f if line.strip()]
def passes(results, threshold=50):
return [r for r in results if r >= threshold]
def summarise(p, total):
return f"{len(p)} out of {total} passed ({len(p) / total:.0%})"
results = read_results("exam.txt")
print(summarise(passes(results), len(results)))
Every function can be tested on its own. That is the whole point of the plan.
Mastery means
- Breaks a problem down into steps and functions before coding
- Identifies the input and output of every part
Sign in to do the exercises and build your mastery up.
Sources
- The Python documentation (PSF licence) — PSF
- CS Unplugged (CC BY-SA 4.0) — CC BY-SA 4.0