HomeCourseModule 05 › Scope — where variables live

Scope — where variables live

Module 05 · Functions7 min readBeginner

What you'll learn

  • Distinguish local from global variables
  • Avoid the global keyword unless you really need it
  • Pass values in / return values out — the clean pattern

Local scope

Variables created inside a function only exist inside that function. Once it returns, they're gone.

def calc():
    temp = 42
    return temp * 2

result = calc()
print(result)   # 84
print(temp)     # NameError — temp doesn't exist out here

Why this is good

It means a function is a self-contained box. Whatever it does inside can't accidentally rename or corrupt a variable you have outside. Imagine the alternative — every function in a million-line program clobbering each other's variables.

Reading a global is OK; changing one is sketchy

TAX_RATE = 0.08   # global constant

def add_tax(amount):
    return amount * (1 + TAX_RATE)   # OK to read
# Bad pattern — reaching outside to change a global
TOTAL = 0
def add(n):
    global TOTAL
    TOTAL += n

# Good pattern — return the new value, let the caller decide
def add(total, n):
    return total + n

The mental model

A clean function takes its inputs as parameters and gives its output as a return value. It doesn't reach out into the world. It's predictable, testable, and reusable. Treat global like cigarettes — legal, occasionally unavoidable, mostly a sign you should reconsider.

Key takeaways

  • Variables created in a function only exist while the function runs.
  • Globals are fine for read-only constants; avoid global for assignment.
  • Inputs in → outputs out: the cleanest function pattern.

Refactor

RUNNING_TOTAL = 0

def add_invoice(amount):
    global RUNNING_TOTAL
    RUNNING_TOTAL += amount
    return RUNNING_TOTAL

Rewrite without the global. Pass the running total in, return the updated value.

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.