Lesson 2 of 5
Read the program by following the data
The agent delivered a program for the specification in lesson 1. Before asking whether it is well designed, read it the way its data moves: what comes in, what each step does to it, where anything is kept, and what comes out. This lesson introduces the handful of programming words that reading needs, at the point where each is first used, and shows the program in pieces along that path; the whole program is at the end for reference. Everything shown was run offline on 2026-09-29 under Python 3.10.4 on the temporary quote files printed here, and every output quoted is what those runs printed.
Numbered links identify sources. Underlined terms offer a definition without leaving the lesson.
The words needed to read it
A in this module is a text file of instructions that Python, an interpreter installed on the organizer's laptop, carries out from top to bottom. A few kinds of instruction cover almost everything in it.
A is a named block of instructions that takes inputs, called arguments, does something with them and hands back a result, called its return value. installed_price(row) is a call of the function named installed_price with one argument, the row; whatever the function returns takes the call's place. Defining functions lets the program be read a piece at a time, and lets a check call one piece without the others.
A list is an ordered collection of values, written in square brackets. A dictionary is a collection of named values, so that row["price"] means the value stored under the name price in the dictionary row. A loop, written for number, row in rows:, runs its block once for each item in a collection. An import line at the top brings in a module, a body of ready-made functions that ships with Python; csv reads comma-separated files, sys reaches the command line, and decimal handles money.
An exception is how Python signals that an instruction could not be carried out: the instruction stops, and the exception travels outward through the calling functions until some except block catches it, or until it reaches the top and the program ends with a printed traceback, a list of the calls it was inside. raise ValueError("...") creates an exception deliberately, with a message. Finally, a program that runs from a has two output channels, standard output for its answer and standard error for messages about problems, and it ends with an exit status, a number the terminal or a calling program can read. Those five words, function, dictionary, loop, exception and channel, are enough for the rest of the lesson.
Input: from a file to records
The begins with the function that reads the file.
def read_quotes(path):
"""Return (record_number, record) pairs. The header is record 1, so data starts at 2.
A quoted field may span lines, so this is a record number, not always a line number."""
with open(path, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
if reader.fieldnames != COLUMNS:
raise ValueError(f"header must be exactly: {','.join(COLUMNS)}")
return [(number, row) for number, row in enumerate(reader, start=2)]
open opens the file at the given , ready for the CSV reader to read it. csv.DictReader reads the first line as the column names and then yields one dictionary per , keyed by those names. A record is one supplier's quote as a unit; a line is one line of text in the file. The two usually coincide, and the difference matters exactly when they do not. If the column names are not exactly the seven the contract requires, which is also what an empty file produces, the function raises an exception naming the required header, and nothing is compared.
Hedgerow's name, "Hedgerow Fencing, Ltd", contains a comma. In the file it is written inside double quotes, and the reader treats the quoted comma as part of the field rather than as a separator. A program that split each line at commas would produce an extra value for that row and shift every later value one place to the right, so the price would land in the installation column; module 5 explained why a CSV reader is used instead. The Python documentation for the module states that quoted fields may contain the delimiter and embedded newlines, and that the file should be opened with newline='' so that the reader, not the operating system, decides where a record ends (csv module documentation, checked 2026-09-29). Both details are in read_quotes for that reason.
Each record gets a number from enumerate(reader, start=2): the header is record 1, so the first quote is record 2. On a temporary file where Northfence's name was written across two lines inside quotes, the reader still produced two records numbered 2 and 3, and the installed prices were correct. The printed table, however, was misaligned, because the table formatter pads a name that now contains a line break. That is an observed behavior outside the input contract, recorded here rather than hidden: nobody decided what a multi-line name should look like in the output, so the program has no considered behavior for it.
Transformation: what happens to each record
Two small functions turn text into amounts.
def money(text):
"""A non-negative amount in pounds, or a ValueError naming the problem."""
try:
amount = Decimal(text)
except InvalidOperation:
raise ValueError(f"'{text}' is not a number")
if not amount.is_finite() or amount < 0:
raise ValueError(f"'{text}' is not a non-negative amount")
return amount
def installed_price(row):
"""What the garden would pay with installation, as a Decimal."""
included = row["installation_included"].strip().lower()
if included == "yes":
return money(row["price"])
if included == "no":
if row["installation_price"] == "":
raise ValueError("installation_price is needed when installation is not included")
return money(row["price"]) + money(row["installation_price"])
raise ValueError(f"installation_included must be yes or no, not '{row['installation_included']}'")
money converts text such as 2150 into a Decimal, a number type that stores decimal digits, and refuses anything that is not a number, is negative, or is not finite. installed_price is where lesson 1's decisive question lives: yes means the quoted price alone, no means the quoted price plus the installation price, which must then be present, and anything else is refused with a message. It is a few lines, and a reader should be able to point to them.
compare takes the numbered records and the requested length and produces two lists, results that can be compared and problems that cannot.
def compare(rows, length_m):
"""Split rows into comparable results and reported problems."""
results, problems = [], []
for number, row in rows:
try:
if row.get(None) is not None:
raise ValueError("more values than columns")
missing = [name for name in COLUMNS if row[name] in (None, "")
and name != "installation_price"]
if missing:
raise ValueError("missing " + ", ".join(missing))
if Decimal(row["length_m"]) != Decimal(length_m):
raise ValueError(f"quotes {row['length_m']} m, brief says {length_m} m")
results.append({
"supplier": row["supplier"],
"installed_price": installed_price(row),
"delivery_weeks": int(row["delivery_weeks"]),
"guarantee_years": int(row["guarantee_years"]),
})
except (ValueError, InvalidOperation) as problem:
problems.append(f"row {number}: {problem}")
results.sort(key=lambda r: r["installed_price"])
return results, problems
For each record it checks the shape, a row with more values than columns or with a required value missing, then the length, then the prices and the whole-number columns. Every one of those checks signals trouble by raising an exception, and the except line at the bottom of the loop catches all of them the same way: the message is recorded with the record number, and the loop continues with the next record. Nothing about a failed record enters the results. When the loop ends, the results are sorted by installed price.
Nothing is stored between runs. The results live in a list in memory and are gone when the process exits, so the program has no of its own that a previous run could have changed. Running it twice on the same file, with the same requested length, the same program text and the same Python installation produced the same output in this lesson's runs, and the reasoning says why: those four things are all the output depends on. Change any of them and the reasoning has to be redone, which is also why module 5's warning about a repeated read returning changed rows applies here the moment the file is edited between runs.
Output and what the caller learns
The last two functions turn results into text and connect everything to the terminal.
def format_table(results):
lines = ["supplier installed delivery guarantee"]
for r in results:
lines.append(f"{r['supplier']:<22} £{r['installed_price']:>8} {r['delivery_weeks']:>3} wks {r['guarantee_years']:>3} yrs")
return "\n".join(lines)
def main(argv):
if len(argv) != 3:
print("usage: compare_quotes.py QUOTES.csv LENGTH_M", file=sys.stderr)
return 2
try:
rows = read_quotes(argv[1])
except (OSError, ValueError) as problem:
print(f"cannot read quotes: {problem}", file=sys.stderr)
return 2
results, problems = compare(rows, argv[2])
print(format_table(results))
for p in problems:
print("not compared: " + p, file=sys.stderr)
return 1 if problems else 0
if __name__ == "__main__":
sys.exit(main(sys.argv))
main prints the table to standard output and each problem, prefixed "not compared:", to standard error, and it returns an of 1 when any problem occurred, 0 otherwise, and 2 when the file could not be read at all. The three-row file used for the main run was exactly this:
supplier,length_m,price,installation_included,installation_price,delivery_weeks,guarantee_years
Northfence Ltd,40,2150,yes,,3,5
"Hedgerow Fencing, Ltd",40,1980,no,300,6,2
Parkside Fencing,38,1900,yes,,4,3
With the requested length 40, the run printed this table on standard output:
supplier installed delivery guarantee
Northfence Ltd £ 2150 3 wks 5 yrs
Hedgerow Fencing, Ltd £ 2280 6 wks 2 yrs
and this on standard error, with exit status 1:
not compared: row 4: quotes 38 m, brief says 40 m
The two channels carry different meanings. Standard output is the answer; standard error is what went wrong; the exit status tells a caller that cannot read prose, such as a scheduled job or a harness, whether the answer is complete. The organizer sees Hedgerow's installed total of 2280, which lesson 1's example demanded, and sees that Parkside was left out and why.
The second temporary file collects the edge cases from lesson 1:
supplier,length_m,price,installation_included,installation_price,delivery_weeks,guarantee_years
Northfence Ltd,40,"2,150",yes,,3,5
Weald Fences,40,2400,no,,5,10
"Hedgerow Fencing, Ltd",40,1980,no,300,6,2
Millbrook Timber,40,2100,included,,4,3
On it, the run printed a table containing Hedgerow alone, and on standard error, with exit status 1:
not compared: row 2: '2,150' is not a number
not compared: row 3: installation_price is needed when installation is not included
not compared: row 5: installation_included must be yes or no, not 'included'
The partial result was labelled as partial, which is the behavior the edge cases asked for. A run on a file that does not exist printed cannot read quotes: [Errno 2] No such file or directory: 'nope.csv' on standard error and exited with status 2.
Reading this way generalizes to most small programs: find where data enters, follow each transformation, look for anything kept between runs, and find every place output leaves. Labels such as "input layer" or "model" are useful once you can say what each one does to the data; used before that, they describe a shape without predicting a behavior. The method has limits. A program that keeps state, talks to a network or runs several things at once has more than one path through it, and following the data means following each path and asking how they interact. Those programs are the reason the next lesson looks at boundaries. The whole program, for reference, is the four pieces above in order, preceded by this header:
"""Compare fencing quotes. Reads a CSV of quotes, works out each installed
price, prints a table sorted by installed price, and reports every row it
could not compare instead of dropping it."""
import csv
import sys
from decimal import Decimal, InvalidOperation
COLUMNS = ["supplier", "length_m", "price", "installation_included",
"installation_price", "delivery_weeks", "guarantee_years"]
Carry this forward
- Read a program along its data path: input, each transformation, anything kept between runs, and every output, before reaching for architecture labels.
- A record is one unit of data; a line is one line of text. A CSV reader keeps a quoted comma or newline inside its field, which splitting at commas does not.
- Every decision from the specification should be findable in the code; the installed-price rule is a few lines in one function, and a reader should be able to point to them.
- Output has channels with meanings: the answer on standard output, problems on standard error, and an exit status for callers that cannot read prose.
- The same file, requested length, program text and Python installation produced the same output; behavior outside the input contract, such as a multi-line name, was observed and recorded rather than decided.
Lesson check
Choose an answer for each question.
This is a practice check. Answers reset when you leave this page. Results are not saved and do not place you in another module or award a qualification.
The program works for its specification, but several of its choices could have gone another way: one function or several, Decimal or floating point, the modules that ship with Python or a downloaded package. The next lesson compares such alternatives by their consequences rather than by taste.
Sources · Reviewed 2026-09-29
Sources support nearby explanations. Product details can change. Scenarios and model results are authored illustrations unless a lesson explicitly identifies a recorded execution. Module 7 identifies its offline code checks.