Where a variable lives: locals are born and die inside functions, globals are shared, and same names shadow each other.
01
Learning objectives
Define local and global variables and state each one's lifetime.
Predict when a function may read a global variable without declaring anything.
Explain shadowing: a local variable with the same name as a global one.
State that local variables do not survive between calls.
Trace a short program that mixes local and global names.
02
Lesson notes
A variable's scope is the region of the program where its name has meaning. Variables created inside a function are local: they exist from the moment the assignment runs and are destroyed when the function returns. Variables created at the top level of the file are global: they live for the whole run and are visible everywhere, including inside every function body.
Reading a global from inside a function is legal: if rate = 15 is global, then def fee(hours): return hours * rate works — Python looks for rate among the local names first, fails to find it, and then finds it globally. (That local-then-global search is what your book calls the scope resolution order.) But assigning to that same name inside the function does something completely different — it creates a brand-new local variable.
That trap is called shadowing: level = 10 inside a function makes a fresh local level that hides the global one until the function returns. The global keeps its old value — power_up() returning 10 leaves the global level still 3. The global keyword can force real global assignment, but relying on it for many variables makes functions unpredictable; passing parameters in and returning results out keeps every function self-contained.
Locals also do not survive between calls. A function that sets count = 0, adds one and returns it will return 1 every single time, because each call builds a fresh count from scratch and discards it at return. If you need memory across calls, keep the state in a global variable or pass it in as a parameter — no call ever remembers another call's locals.
Why does Python bother with all this? Independence. Because locals are private, two functions can both use a variable named total without ever corrupting each other, and to read a function you only need its parameters and its return value — not the rest of the file. Board tip: trace questions love mixed scopes; annotate every name L or G as you read the code, then predict the prints.
03
Worked code examples
Shadowing: the local hides the global
The assignment inside the function creates a new local level; the global level is untouched, so the print shows 3 and 10.