Nested Functions
def outer(x):
def inner(y):
return x + y
return inner
add5 = outer(5)
print(add5(10)) # 15
What Is a Closure?
A closure is a function that remembers variables from its surrounding scope, even after the outer function has returned.
Why Use Them?
- Creating customised functions on the fly.
- Encapsulating state without a class.
- Callback factories.
Counter Example
def make_counter():
count = 0
def inc():
nonlocal count
count += 1
return count
return inc
c = make_counter()
print(c(), c(), c()) # 1 2 3
Practise this on PyForm — free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm →