Python Scope

Scope refers to the region of a program where a variable is accessible. Python has different types of scope, including local scope, global scope, and built-in scope. Understanding scope helps in avoiding variable conflicts and managing variable visibility.


Local Scope

Variables defined inside a function have a local scope, meaning they are only accessible within that function.

Explanation of Code:

In this example, x is a local variable and can only be accessed inside my_function.

def my_function():
    x = 10  # Local variable
    print(x)

my_function()  # Output: 10
# print(x)  # This would raise an error because x is not defined outside the function




Global Scope

Variables defined outside any function have a global scope, meaning they are accessible throughout the entire program.

Explanation of Code:

In this example, x is a global variable and can be accessed both inside and outside my_function.

x = 20  # Global variable

def my_function():
    print(x)

my_function()  # Output: 20
print(x)       # Output: 20




Modifying Global Variables

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

Explanation of Code:

The global keyword allows you to reference the global variable inside the function. In this example, the global keyword is used to modify the global variable x inside my_function.

x = 20  # Global variable

def my_function():
    global x
    x = 10
    print(x)

my_function()  # Output: 10
print(x)       # Output: 10




Enclosing Scope

Enclosing scope refers to variables defined in a function that is within another function. These variables are accessible to the inner function.

Explanation of Code:

This is also known as the non-local scope. In this example, y is an enclosing variable and can be accessed by inner_function.

def outer_function():
    y = 30  # Enclosing variable

    def inner_function():
        print(y)

    inner_function()

outer_function()  # Output: 30




Built-in Scope

Built-in scope refers to names preassigned by Python. These names are always available, regardless of the scope.

Explanation of Code:

The len function is an example of a built-in function available in the built-in scope.

print(len([1, 2, 3]))  # Output: 3




Python Labs

Scroll to Top