
Code
Closures & nonlocal
A function defined inside another function can use the outer function's variables, even after the outer function has returned. That inner function plus the variables it remembers is a closure.
def make_greeter(greeting):
def greet(name):
return f"{greeting}, {name}!"
return greet
hello = make_greeter("Hello")
hello("Ada") # 'Hello, Ada!' -- greeting is remembered
Reading an outer variable just works. Rebinding it (x = ...,
x += 1) would normally create a new local variable instead, so you
must declare it nonlocal:
def make_meter():
total = 0
def add(n):
nonlocal total # use the outer 'total'
total += n
return total
return add
Each call to make_meter() creates a fresh total, so two meters
never interfere. Closures are a lightweight way to bundle a little
private state with behavior, and they are exactly how decorators work.
Assignment
- Finish
make_counter(): each call to the returnedtick()returns the next number, starting at1. - Write
make_tank(litres)that returns a functiondraw(amount):- if
amountis more than what's left, raiseValueError("not enough fuel")and leave the tank unchanged; - otherwise subtract it and return the litres remaining.
- if
- Finish
make_counter(): each call to the returnedtick()returns the next number, starting at1. - Write
make_tank(litres)that returns a functiondraw(amount):- if
amountis more than what's left, raiseValueError("not enough fuel")and leave the tank unchanged; - otherwise subtract it and return the litres remaining.
- if
main.py Python sleeping
Press Run to try your code, then Check to test it.