python · level 3 · unit 2 · lesson 3
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A is a function that remembers where it was made.
You can define an inside another one and return it. The inner function can read the outer function's variables, even after the outer one has finished. A function that carries its surroundings with it like this is a closure.
Each call to the outer function makes a brand new closure with its own memory, so two counters never share a count.
To change a remembered variable, not only read it, the inner function must say first. Without that line, Python treats count as a brand new variable of its own.
def make_counter():
count = 0
def counter():
nonlocal count
count = count + 1
return count
return counter
tickets = make_counter()
queue = make_counter()
print(tickets(), tickets(), tickets())
print(queue()) Closures are how the decorators in the next lesson remember the function they wrap.
guess first
Two machines from one factory. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def make_multiplier(factor):
def multiply(n):
return n * factor
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5), double(triple(2)))
your turn
Your turn. Build a running total for a till.
Fill the first blank so ring may change total. Then ring up two prices of your choice in pence.
fix it
The scorer crashes on its first point. Fix it!
- The error says
pointswas used before it had a value. Whichpointsdoes line 4 mean? - Storing a value in
pointsinsidescoremakes Python treat it as a new variable of its own. - Add
nonlocal pointsas the first line insidescore, then run.
nailed it
your functions remember things now. :D
- An inner function can read the outer function's variables.
- A closure keeps those variables alive after the outer call ends.
- Write
nonlocalbefore changing a remembered variable.
new words in your collection
- inner function
- closure
- nonlocal
This lesson isn’t saved. A free account remembers every lesson you finish.