Functions inside functions (closures)
A function defined inside another can use the outer function's variables, even after the outer one has finished.
Used in 17 lessons of the course, from Project 01.
You can write a def inside another def. The inner function only exists while the outer one runs, unless you return it.
The inner function can read the outer function's names. Python remembers them: this is called a closure. So when the outer function finishes, the inner one still has access to those values.
To read it, find the outer def first and see what it receives. Then look at what the inner one does with those values.
It's written this way because you can fix a piece of data once and reuse the logic later. It also keeps a helper private, without cluttering the rest of the file.
In the course, a line like def answer(prompt_value) -> dict: defines a function that takes a value and returns a dict. Nested functions use the same def form, just inside another function.
Reach for it when: you need a small helper that only makes sense inside another function, or when you want to build a function already set up with a value.
Examples
Common mistake
def outer():
def inner():
return 1
return 2
outer()
print(inner())Why: `inner` only exists inside `outer`. From outside, that name doesn't exist.
How to write it: Return the function with return inner and keep it in a variable, or call it inside outer.
Common mistake
def counter():
count = 0
def add():
count += 1
return count
return add
c = counter()
print(c())Why: Assigning with `+=` makes Python treat `count` as local to `add`, and it has no value yet.
How to write it: Declare nonlocal count at the top of add to change the outer function's variable.
