Variable Scope in Python

Variable scope in Python refers to the region of a program where a variable is accessible or visible. Python has two main variable scopes: global scope and local scope.

  1. Global Scope: Variables defined outside of any function or class have global scope. They can be accessed from anywhere within the module or script where they are defined.

Example of global scope:

pythonCopy codex = 10

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

print_global()  # Output: 10
  1. Local Scope: Variables defined within a function have local scope. They are only accessible within the function in which they are defined.

Example of local scope:

pythonCopy codedef print_local():
    y = 20  # Local variable
    print(y)

print_local()  # Output: 20

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

When a variable is referenced within a function, Python first looks for it in the local scope. If not found, it then looks in the enclosing function's scope, and so on, until it reaches the global scope. If the variable is not found in any of these scopes, a NameError is raised.

However, variables from the global scope can be accessed within a function using the global keyword.

Example:

pythonCopy codex = 10

def modify_global():
    global x
    x = 20

modify_global()
print(x)  # Output: 20

In addition to global and local scopes, Python also has nonlocal scope, which is used for nested functions. Variables in nonlocal scope are not covered in this explanation, as they are less commonly used compared to global and local scopes.

Check out the Free Online Python Tutorial!