Python Local and Global Variable Scope Explained with Examples

In Python, variables can have different scopes, such as local and global scopes.

Local Variable Scope

Variables defined inside a function have local scope and are accessible only within that function.

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

my_func()  # Output: 10

# Attempting to access x outside the function will result in an error
# print(x)  # NameError: name 'x' is not defined

In this example, x is a local variable within the my_func function and can only be accessed within that function.

Global Variable Scope

Variables defined outside of any function have global scope and can be accessed anywhere in the code.

global_var = 100

def my_func():
    print(global_var)

my_func()  # Output: 100

Here, global_var is defined in the global scope and is accessible within the my_func function.

Global Variables Inside a Function

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

global_var = 100

def modify_global():
    global global_var
    global_var = 200

modify_global()
print(global_var)  # Output: 200

Avoiding Unintended Global Variable Creation

If you try to assign a value to a variable inside a function without using the global keyword, Python will create a new local variable with the same name.

x = 5

def create_local():
    x = 10  # This creates a new local variable x
    print(x)

create_local()  # Output: 10
print(x)  # Output: 5 (global x remains unchanged)

In this case, x inside create_local is a local variable, and the global x remains unaffected.