Variable Scope

Scope refers to the region of the code where a variable is accessible.

Types of Scope:

  • Local: Inside a function.
  • Global: Outside all functions.
  • Nonlocal: In nested functions (closure).

Example:

x = "global"

def my_function():
    x = "local"
    print("Inside the function:", x)

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

global and nonlocal:

counter = 0

def increment():
    global counter
    counter += 1
def outer():
    x = "outer"
    def inner():
        nonlocal x
        x = "modified"
    inner()
    print(x)