5.6 Variable Scope

5.6 Variable Scope

Understanding the scope of variables and the LEGB rule (Local, Enclosing, Global, Built-in) to avoid errors and manage data correctly.

The scope of a variable determines the part of the program from which that variable is accessible. Python follows the LEGB rule to find a variable:
  • Local (L): The innermost level, inside a function. Variables defined here are local.
  • Enclosing (E): The scope of outer functions, in case of nested functions.
  • Global (G): The top-level of a Python file. Variables defined here are global.
  • Built-in (B): The scope that contains Python's built-in functions (e.g., `print()`, `len()`).
Python searches for a variable in this order: L -> E -> G -> B. If it doesn't find it, it raises a `NameError`.

global and nonlocal Keywords

Normally, you cannot modify a global variable from a local scope. To do this, you must use the `global` keyword. Similarly, the `nonlocal` keyword is used within a nested function to modify a variable of the immediately enclosing function.
# Global Example
counter = 0

def increment_counter():
    global counter
    counter += 1

increment_counter()
increment_counter()
print(f"Global counter: {counter}")

# Nonlocal Example
def outer_function():
    message = "Outer"
    def inner_function():
        nonlocal message
        message = "Changed!"
    inner_function()
    print(f"Final message: {message}")

outer_function()

Practical Exercises

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.