Scope of Variables in Python

In Python, the scope of a variable determines where it can be accessed or modified. There are four types of variable scopes:

1️⃣ Local Scope
2️⃣ Enclosing (Nonlocal) Scope
3️⃣ Global Scope
4️⃣ Built-in Scope


1️⃣ Local Scope (Inside a Function)

A local variable is declared inside a function and can be accessed only within that function.

Example:

def my_function():
    x = 10  # Local variable
    print("Inside function:", x)

my_function()
# print(x)  # ❌ Error: x is not defined outside the function

Output:

Inside function: 10

📌 Local variables exist only within the function.


2️⃣ Global Scope (Outside Functions)

A global variable is declared outside a function and can be accessed anywhere in the script.

Example:

x = 100  # Global variable

def my_function():
    print("Inside function:", x)

my_function()
print("Outside function:", x)

Output:

Inside function: 100
Outside function: 100

📌 Global variables can be accessed inside functions but cannot be modified directly (unless specified).


3️⃣ Modifying Global Variables Inside a Function (global Keyword)

To modify a global variable inside a function, use the global keyword.

Example:

x = 50  # Global variable

def modify_global():
    global x  # Declare x as global
    x = 200   # Modify global variable
    print("Inside function:", x)

modify_global()
print("Outside function:", x)  # Global variable is modified

Output:

Inside function: 200
Outside function: 200

📌 Without global, Python will treat x as a local variable inside the function.


4️⃣ Enclosing Scope (nonlocal Keyword)

A nested function (a function inside another function) has access to variables in the enclosing (outer) function.

Example:

def outer_function():
    x = 5  # Enclosing variable

    def inner_function():
        nonlocal x  # Modify enclosing variable
        x = 10
        print("Inside inner function:", x)

    inner_function()
    print("Inside outer function:", x)

outer_function()

Output:

Inside inner function: 10
Inside outer function: 10

📌 Use nonlocal to modify a variable in an enclosing function.


5️⃣ Built-in Scope (Python’s Reserved Names)

Python has built-in functions like print(), len(), and sum(). These exist in the built-in scope, which is available everywhere.

Example:

print(len([1, 2, 3]))  # Using built-in len() function

📌 Avoid using built-in names as variables (e.g., sum = 10 would override sum() function).


🔹 Scope Resolution (LEGB Rule)

Python follows the LEGB rule to resolve variable scope:

Scope Example Description
Local (L) Inside a function (x = 10) Defined inside a function
Enclosing (E) Nested function (nonlocal x) Defined in an outer function
Global (G) Outside all functions (x = 100) Defined at the top level
Built-in (B) Python functions (print(), len()) Built-in Python functions

Example Showing LEGB Rule:

x = "Global"

def outer():
    x = "Enclosing"

    def inner():
        x = "Local"
        print(x)  # Local Scope (L)

    inner()
    print(x)  # Enclosing Scope (E)

outer()
print(x)  # Global Scope (G)

Output:

Local
Enclosing
Global

🔹 Summary Table

Scope Description Keyword Used
Local Inside a function, only accessible within it None
Global Defined outside functions, accessible globally global
Enclosing A function inside another function nonlocal
Built-in Python’s built-in functions N/A

Would you like more examples or real-world use cases? 🚀


Leave a Reply

Your email address will not be published. Required fields are marked *