Scope determines where Python can resolve a name. During a function call, Python searches Local, Enclosing function, Global, and Built-ins—the LEGB order—and stops at the first match. Outside functions, only global and built-in namespaces participate; indentation and loops do not create scopes. section 7.5
Use these distinctions when reading or debugging name resolution:
- An assignment inside a function normally creates or updates a local name, leaving a same-named global unchanged. section 7.5
- The global statement makes an assignment target the global name instead of the function-local name. section 7.5
- Built-in names such as int are searched after globals, so rebinding a built-in such as sum can make later calls fail. section 7.5
- An inner function can read an enclosing function's local names; nonlocal permits it to update an enclosing binding. section 7.5 section 7.11
A closure preserves enclosing state
def foo(): call_counter = 0 def bar(y): nonlocal call_counter call_counter += 1 return f'y = {y}, call_counter = {call_counter}' return bar b = foo() print(b(10)) # y = 10, call_counter = 1 print(b(20)) # y = 20, call_counter = 2 The returned function retains access to call_counter from foo's enclosing scope, even after foo returns. section 7.5 section 7.11
x = 100
def foo():
x = 200
print(x)
print(x)
foo()
print(x)
Compare inner and outer x values to see local shadowing without global mutation. section 7.5




















