Python Variable Scope

Deep dive into variable scope.

Python - Variable Scope:

Variable scope refers to the region of a program where a variable is accessible. Understanding scope is crucial for writing clean, bug-free code. In Python, there are mainly two types of variable scope: global scope and local scope.

1. Global Scope:

Variables declared outside of any function or class have global scope.

They can be accessed from anywhere within the program, including inside functions and classes.

To modify a global variable from within a function, you need to use the 'global' keyword.

PDF Copy Code
# Python variable scope: Global
x = 10  # Global variable

def func():
    print(x)  # Accessing global variable

func()  # Output: 10

2. Local Scope:

Variables declared within a function or a class have local scope.

They can only be accessed from within that function or class.

Variables with the same name can exist both globally and locally without affecting each other.

def func():
    y = 20  # Local variable

func()  # Output: 20

# Accessing local variable outside the function will result in NameError
print(y)  # NameError: name 'y' is not defined

[Error] NameError: name 'y' is not defined

However, Python also supports a concept called "enclosing scope," which comes into play with nested functions. In the case of nested functions, a variable declared in an outer function is accessible in the inner function.

PDF Copy Code
# Python variable scope: Local
def outer_func():
    z = 30  # Enclosing scope variable

    def inner_func():
        print(z)  # Accessing enclosing scope variable


outer_func()  # Output: 30

Note: You can also use the 'nonlocal' keyword, which allows you to modify variables in the enclosing scope from within nested functions.

nonlocal x
        x = 20  # Modifying variable in the enclosing scope

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.