Explain the LEGB rule Python uses to resolve a name reference.
Answer
Python looks up a bare name in four scopes in order: Local (the current function), Enclosing (any enclosing function, for closures), Global (the module's top level) and Built-in (Python's built-in namespace). Resolution stops at the first scope where the name is found, so a local variable shadows a global with the same name, and a name that is assigned anywhere inside a function is treated as local for the whole function unless declared `global` or `nonlocal`.
Strong answer includes
- Local, Enclosing, Global, Built-in order
- first match wins
- assignment anywhere makes a name local
Practical example
If a function assigns
count = count + 1without declaring `global count` , Python raises UnboundLocalError, because the assignment marks `count` local for the entire function body, including the read before the assignment.