Chapter 49: Functions as Contracts
James has typed variables, strings, and collections. He can read function signatures and complete a single TDG cycle. Now it is time to write richer function signatures: multiple parameters, return types, defaults, and docstrings. Each signature is a contract that tells AI exactly what to build.
Emma opens a blank file. "Write me a function that calculates reading time."
James types def reading_time(): and pauses. "What goes inside the parentheses?"
"Everything the function needs to do its job. The word count. The reading speed. Their types. The return type. That signature is your specification. Get it right, and AI writes the body. Get it wrong, and AI guesses." She taps the screen. "Guessing is how bugs start."
Over the next four lessons, James writes function signatures with multiple typed parameters, learns the difference between return and print, adds default values and keyword arguments, writes docstrings that describe what a function does (not how), and completes a full TDG cycle with SmartNotes functions using dict[str, str].
What You Will Learn
| Lesson | Topic | Duration | What You Will Do |
|---|---|---|---|
| 1 | Parameters and Return Types | ~25 min | Write multi-parameter signatures, understand return vs print, learn indentation |
| 2 | Default Values and Keyword Arguments | ~20 min | Add defaults, call with keyword args, read one if preview |
| 3 | Docstrings: The Human-Readable Spec | ~15 min | Write docstrings that describe what, not how |
| 4 | Writing Real Specifications | ~25 min | Full TDG cycle with SmartNotes stubs, tests, and AI-generated bodies |
| 5 | Chapter 49 Quiz | ~25 min | 50 scenario-based questions covering all lessons |
Prerequisites
Before starting this chapter, you should be able to:
- Write type annotations for
int,float,str,bool, andNone(Chapter 47) - Read and write
list[str],dict[str, str], and other collection types (Chapter 48) - Complete a single TDG cycle: stub, test, prompt AI, verify (Chapter 46)
- Run pyright and pytest from the terminal (Chapter 44)
Design Constraint
All AI-generated function bodies in this chapter are straight-line code: no if, for, while, or comprehensions. One exception in Lesson 2 previews a single if statement with an explicit note. Control flow is taught in Phase 3.