Why can a function freely read a global variable, yet raise UnboundLocalError the instant you try to assign to that same name?
Short drills on what this video just taught. Write the code, run the checks, and reveal the answer only if you are stuck.
Define a function subtract(a, b) that returns a - b. Two values are given: x = 10 and y = 3. Call your function so that it computes 10 minus 3 — think about which argument lands on which parameter — and assign the returned value to diff.
The function as a black box
State the split between the person who writes a function and the person who uses it, and record that the docstring specification is all a caller of sum_odd or bisection_root needs.
The environment created by each call
Trace x = 3 then z = f(x) for a function whose body is x = x + 1, recording the new scope binding x to 3, the printed 4, z = 4, and the scope disappearing.
Reading an outer variable from an inner scope
Run the f and g examples with global x = 5, recording outputs 2 then 5, and 5 then 6 then 5, and state that Python searches outward when a name is missing locally.
UnboundLocalError and the global keyword
Write the h example whose body is x = x + 1, record the UnboundLocalError it raises, and state that assigning to a name makes it local unless global is declared.