Scope in Python
Scope defines where a variable is accessible in your code. Python follows the LEGB rule when looking up variable names: Local → Enclosing → Global → Built-in.
Understanding scope prevents bugs and helps write cleaner, more predictable code. We'll explore each level with examples.
Local Scope
Variables defined inside a function are local – only accessible within that function.
Enclosing Scope (Nested Functions)
In nested functions, the inner function can access variables from the outer function.
Global Scope
Variables defined at the top level (outside functions) are global – accessible anywhere.
Modifying Global Variables – global Keyword
To modify a global variable inside a function, use the global keyword.
nonlocal Keyword – For Enclosing Scope
nonlocal lets inner functions modify variables in the enclosing (outer) function.
The LEGB Rule
Python looks up variables in this order:
- Local (inside current function)
- Enclosing (in nested functions)
- Global (module level)
- Built-in (Python's built-in names like print, len)
Common Pitfalls
- UnboundLocalError – reading a variable before assigning in local scope
- Shadowing built-in names (avoid naming variables print, list, etc.)
Quick Quiz
Hemos revisado y comprobado los materiales, pero aún pueden existir errores. El contenido se ofrece únicamente con fines educativos, así que úsalo bajo tu propia responsabilidad y verifica con otras fuentes si es necesario.
✨ Pregunta a Lara — tu compañera de estudio con IA
Desbloquea soporte de aprendizaje personalizado. Lara puede explicar lecciones, resumir temas y responder tus preguntas — disponible desde el plan Go y superiores.
Lara te ayuda a aprender más rápido — exclusivo para los miembros ReadyTools Go, Plus y Max.

