Python Basics — Scope & Closures

1 minute read

Scope & Closures

Understanding scope — where variables live and how long they exist — is essential for writing correct, bug-free Python code. This chapter covers how Python resolves variable names and introduces closures, a powerful pattern that combines functions with their surrounding state.

What You’ll Learn

# Topic What You’ll Master
1 Local & Global Scope Variables inside vs outside functions
2 LEGB Rule Python’s name resolution order
3 global & nonlocal Modifying outer variables from inner scopes
4 Closures Functions that remember their environment
5 Scope Best Practices Writing clean, maintainable scoped code
6 Practice Exercises Test your understanding

Quick Preview

# A closure — a function that remembers its enclosing scope
def make_multiplier(factor):
    def multiply(number):
        return number * factor  # factor is "closed over"
    return multiply

double = make_multiplier(2)
triple = make_multiplier(3)

print(double(5))   # 10
print(triple(5))   # 15

Why Scope Matters

Problem Caused By Solution
UnboundLocalError Assigning to a variable that shadows a global Use global keyword or pass as argument
Unexpected value changes Modifying a global from inside a function Avoid mutable globals; pass data explicitly
Hard-to-debug code Relying on global state Keep functions pure — input in, output out
Stale data in closures Late binding in loops Use default arguments or functools.partial

Start Learning: Local & Global Scope →

Updated: