Scope in Python

LambdaImports

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

We have reviewed and checked the materials, but errors may still occur. The content is provided for educational purposes only, so use it at your own responsibility and verify with other sources if needed.

✨ Ask Lara — your AI study partner

Unlock personalized learning support. Lara can explain lessons, summarize topics, and answer your study questions — available from the Go plan and above.


Lara helps you learn faster — exclusive to ReadyTools Go, Plus, and Max members.

Track Your Progress 🚀

Learn more easily by tracking your progress completely for free.