Local and Global Names in Python
Core idea
A scope determines where a name can be resolved. In ordinary functions, Python searches local bindings, enclosing function scopes, the module’s global namespace, then built-ins (LEGB). A parameter is local; reading a global name does not require a declaration.
rate = 3def cost(units): return units * rateprint(cost(4))units is a local parameter; rate resolves to the module binding.
Keep a local calculation separate
total = 20def estimate(): total = 5 return total + 2print(estimate())print(total)The function binds its own total. The module-level total remains 20.
Intentional failure: read before binding
count = 8def update(): print(count) count = 9update()Because count is assigned in the function, it is local throughout that function. Reading it before assignment raises UnboundLocalError.
Common mistake
An if block does not introduce a separate ordinary function scope. Do not expect a global value to be read merely because the local assignment occurs later.
Practice
Change the module rate to 6 and predict the result. Rewrite update to take a count parameter and return count + 1 without modifying the global name.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Resolve local and global names
Check your understanding of local and global names.
What is printed?
rate = 2def cost(): return 3 * rateprint(cost())What is printed?
n = 9def f(): n = 2 return nprint(f(), n)Which exception is raised?
x = 5def f(): x = x + 1f()Where is an ordinary function parameter bound?