In Python, scope determines where a variable can be accessed or modified. Scope follows the LEGB Rule, which stands for:
Local → Enclosing → Global → Built-in
When Python encounters a variable, it searches in this order:
- Local — inside the current function
- Enclosing — in any outer functions
- Global — at the top level of the script/module
- Built-in — names like len(), sum(), etc.