Functions, Parameters and Returns
- def. The def statement binds a name to a function object; return hands one value back and ends the call.
- Default and keyword arguments. Parameters may carry defaults, and callers may name arguments: send(subject, body, urgent=True) reads like prose.
- args and kwargs. The starred args and kwargs forms collect extra positional and keyword arguments into a tuple and a dict.
Scope and Name Resolution
- LEGB. Python resolves a name through LEGB: local, enclosing, global, then built-in: the first hit wins.
- The global trap. Assigning inside a function creates a local name by default: rebinding a global needs an explicit declaration.
- Mutable default trap. A mutable default like def f(items=[]) is created once and shared by every call: the classic Python interview bug.
Functional Patterns and Lambdas
- Lambdas. A lambda is a one-expression anonymous function: perfect as a sort key, wrong for anything with logic.
- Functions as values. Functions are objects: pass them, store them, return them: sorted(users, key=by_age) hands a function to a function.
- map, filter and friends. map and filter exist, but Python idiom usually prefers a comprehension saying the same thing more readably.
Before and after this level
- Before: Level 3: Python Collections: Lists and Tuples, Dictionaries and Sets, Comprehensions and Collection Patterns.
- Next: Level 5: Modules & Packages: Modules and Imports, Packages and Project Structure, Virtual Environments and Dependencies.
In the app each of these ideas is taught and then asked back, and the level ends with a checkpoint and flashcards. See Checkpoints and flashcards.
Frequently asked questions
What does Python Level 4: Functions & Scope cover?
Functions, Parameters and Returns, Scope and Name Resolution, Functional Patterns and Lambdas: 3 lessons and 9 ideas.
What should I know before this level?
The level before it, Level 3: Python Collections, which covers Lists and Tuples, Dictionaries and Sets, Comprehensions and Collection Patterns.