Q10: What is the LEGB Rule for Python scope resolution?
Python resolves variable names in strict sequential order:
- L (Local): Inside active function/lambda body.
- E (Enclosing / Nonlocal): In enclosing nested function scopes.
- G (Global): At module top-level.
- B (Built-in): Preloaded Python built-in names (
len,range).
Key Takeaways
- Scope resolution order: Local -> Enclosing -> Global -> Built-in.
- Use
globalornonlocalkeywords to rebind variables in outer scopes.
Knowledge Check
Which keyword must be used inside a nested inner function to rebind a variable declared in its parent outer function scope?