Lecture Notes — Lecture 14: Functions with Purpose

Companion to the lecture plan and the worked examples. Read the Definitions before class, the Explanation after it; the practice questions and the lecture quiz close the loop.

Definitions

Explanation

Functions are nouns for computation. Naming a computation (parse_score, average_of) lets you reason about it, test it, and compose it without holding its body in your head.

The contract sentence. Every function gets one line: needs / does / returns. If you cannot write it, the function does not yet have one job - split it.

Pure helpers make pipelines. Functions that only return values can be chained and tested independently; printing inside helpers breaks both. The pipeline case shows text flowing through clean -> tokenise -> count.

Refactoring is behaviour-preserving surgery. The rule: tests first (green), restructure, tests again (still green). The monolith-to-functions case is done live under this discipline.

Return, do not print. A printing function returns None and cannot be composed. The rule of thumb taught: helpers return; the main script prints.

Examples

The lecture's worked examples live in examples.md; the case studies this lecture builds on are worked in class from the projector. The case sequence with difficulties:

Common misconceptions

Summary and key takeaways

  1. One function, one job, one sentence contract.
  2. Helpers return values; the main script prints.
  3. Refactor under test: green, restructure, green.
  4. Pipelines emerge from pure helpers chaining output to input.

Practice questions

Where this leads

Next lecture: Counting, Combinatorics, and Choice. The quiz below checks this lecture's essentials before we build on them.