Module 3: Functions
Package code into reusable functions with parameters and return values, understand scope, and use modules like math and random.
- Writing functions: def makes a function, a call runs it; return hands a value back (no return means None); defaults go last in the header, keywords go last in the call.
- Scope and flow of execution: Names assigned inside a function are local to that call; reading a global is fine, assigning to it needs global (or better, return the new value).
- Modules: math, random and friends: import m → m.f(), from m import f → f(); randint(a, b) includes b, randrange(a, b) doesn't; guard demo code with if name == "main":.
- Good functions: one job, docs and tests: One job per function, a docstring on top, and assert condition, "message" tests (no brackets) for normal, edge and boundary cases.
Ends with a 13-question checkpoint (80% passes) and a mini project: Canteen Counter: the bill as functions.