Scope
Variables created inside a function are local: they live in that call's frame and vanish when it returns. Code inside can read globals, but assigning to a name makes it local.
count = 0 def bump(): count = count + 1 # UnboundLocalError!
Fix it either way:
- better: pass the value in and
returnthe new one - or declare
global countinside the function
A function can be defined inside another function. The inner one can read the outer one's variables; to assign to one of them, declare it nonlocal (like global, but for the enclosing function):
def make_counter(): count = 0 def tick(): nonlocal count # use make_counter's count count += 1 return count return tick # the function itself, no brackets
c = make_counter() stores the returned tick function, so each c() adds 1 to the same count.
See it run
count = 0 nums = [1] def change(box): count = 99 box.append(2) change(nums) print(count, nums)
The change() box has its own names. See which of its changes reach the caller.
Practice scope
Exercise 1
The add_one function in the code editor below crashes when called. Fix the program so count ends at 2 and 2 is printed.
Exercise 2
Avoid global state in a step counter. advance(current, steps) returns the new count without changing global count = 10. Store advance(count, 3) in after_walk, then advance(after_walk, 2) in after_run.
Exercise 3
reserve(stock, requested) returns the remaining stock after taking requested items, or the unchanged stock if the request is larger than what is left. It never changes anything outside the function. For example, reserve(8, 3) is 5 and reserve(5, 6) is 5.
Exercise 4
Predict, then verify. Read this program before running it:
def add_bonus(scores): scores.append(10) scores = [0] return scores
team = [5, 7] result = add_bonus(team)
What do team and result hold at the end? Guess, then set team_prediction and result_prediction. Run it, press Step through your code, and watch the #number of scores inside the add_bonus() box on each line.
Exercise 5
In the editor below, make_counter() creates a local count and returns an inner tick() that should add 1 to that count and return it. Right now c() crashes with UnboundLocalError. Add one nonlocal line so first is 1 and second is 2. A new counter made with make_counter() must start again from 1.
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.