Python Scope

A variable is only available from inside the region it is created. This is called scope. Python has local, enclosing, global, and built-in scopes, often referred to as the LEGB rule.

Example 1: Local Scope

Variables created inside a function are local to that function.

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

my_function()
# print(x)  # This would raise an error

Inside function, x = 10

Example 2: Global Scope

Variables created outside of a function are global and can be used by any function.

# Global scope
x = 20
def my_function():
    print("Inside function, x =", x)

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

Inside function, x = 20

Outside function, x = 20

Example 3: Enclosing Scope

Variables in the outer function can be accessed by inner functions.

# Enclosing scope
def outer_function():
    y = "Hello"
    def inner_function():
        print(y)
    inner_function()

outer_function()

Hello

Example 4: Global Keyword

Use the global keyword to modify a global variable inside a function.

# Using global keyword
y = 5
def change_global():
    global y
    y = 10

change_global()
print("y =", y)

y = 10

Example 5: Nonlocal Keyword

Use the nonlocal keyword to modify a variable in the enclosing scope.

# Using nonlocal keyword
def outer_function():
    x = "Hello"
    def inner_function():
        nonlocal x
        x = "Hi"
    inner_function()
    print("x =", x)

outer_function()

x = Hi

Example 6: Built-in Scope

Accessing built-in functions and variables.

# Built-in scope
print("Maximum of [1, 5, 3]:", max([1, 5, 3]))
print("Length of 'Tamil':", len("Tamil"))

Maximum of [1, 5, 3]: 5

Length of 'Tamil': 5

Explanation: Understanding scope is crucial for variable management in functions and classes. The global and nonlocal keywords allow modification of variables in the global and enclosing scopes, respectively.