HOME HTML EDITOR C JAVA PHP python

Python Scope

A variable's scope determines where in your program that variable can be accessed or modified. Python resolves variable names in a specific order known as the LEGB rule: Local, Enclosing, Global, and Built-in.

1. Local Scope

A variable created inside a function belongs to that function's local scope and can only be used inside that function:

def show_score():
    score = 95  # Local variable
    print("Inside function:", score)

show_score()

2. Global Scope & the global Keyword

A variable defined at the top level of a script has global scope. To modify a global variable inside a function, declare it with global:

visits = 100  # Global variable

def add_visit():
    global visits
    visits += 1

add_visit()
print("Total visits:", visits)  # Output: Total visits: 101

3. Enclosing Scope & the nonlocal Keyword

When a function is nested inside another function, the inner function can access variables in the outer (enclosing) function, and use nonlocal to modify them:

def outer():
    count = 0

    def inner():
        nonlocal count
        count += 1
        return count

    print("First call:", inner())   # Output: 1
    print("Second call:", inner())  # Output: 2

outer()
Tip: Passing values as function parameters and returning results is usually cleaner and safer than relying heavily on global variables.