>> Module 01 / Day 13 / Lecture

Scope — Local vs Global

Day 13 of a 40-day journey
Where does a variable live, and where does it die? Get this right and your functions become tidy little machines. Get it wrong and bugs hide in plain sight.
Lecture
75 min · 09:00–10:15
Lab
60 min · Scope Bug-Hunt
Module
M1 · Python Foundations
DAY 13 / 40
>> 01 · The big idea

What is "scope"?

Scope is the part of your program where a variable name actually exists and can be used. A name born inside a function isn't visible outside it — and that's a feature, not a bug.

Mental model. Think of each function as a room. Variables you create in that room are only visible while you're inside it. Walk out, and they're gone.
>> 02 · Local scope

Local variables live and die inside a function

A variable created inside a function exists only while that function runs. The moment the function returns, the name vanishes.

local.py
def greet():
    message = "hi there"   # local to greet()
    print(message)

greet()                  # hi there
print(message)          # NameError: not defined
It's gone.
message only exists inside greet(). Outside, Python has never heard of it.
>> 02 · Local scope, continued

Parameters are local too

The same name in two functions is two different variables. They never collide — each lives in its own room.

two_rooms.py
def double(x):       # this x is local to double()
    return x * 2

def shout(x):        # a DIFFERENT x, local to shout()
    return str(x) + "!"

print(double(5))     # 10
print(shout(5))      # 5!
# The two x's never see each other.
>> 03 · Global scope

The global scope

A variable defined at the top level of your file — not inside any function — is global. Functions are allowed to read it.

global_read.py
TAX_RATE = 0.05        # global, top level

def with_tax(price):
    return price * (1 + TAX_RATE)

print(with_tax(80))   # 84.0
Reading is OK… sometimes.
A fixed constant like TAX_RATE is a fine global. The trouble starts when globals change.
>> 04 · The fragile part

Why leaning on globals is fragile

A function that reads a changing global gives different answers depending on what happened earlier. You can't trust it just by reading it.

fragile.py
total = 0

def show_total():
    print(f"Total is {total}")   # reads the global

show_total()           # Total is 0
total = 999            # something far away changes it
show_total()           # Total is 999  — same call, different answer!
>> 05 · The `global` keyword

global is usually a code smell

To reassign a global from inside a function you'd need the global keyword. The fact you reached for it is a warning sign.

smell.py
total = 0

def add_item(price):
    global total          # reaching out to mutate the global
    total = total + price  # now two callers fight over `total`

# Works for ONE cart. Add a second cart and they corrupt each other.
>> 06 · The rule to live by

Pass it in. Return it out.

Whatever a function needs, hand it in as a parameter. Whatever it produces, hand back with return. No reaching out to globals.

FRAGILE
total = total + price
# reads & writes a global
CLEAN
return running + price
# in via params, out via return
>> 07 · Worked example

Buggy vs fixed — the cart total

buggy.py
total = 0

def add_item(price):
    global total
    total = price   # overwrites!
    return total

add_item(40); add_item(25); add_item(15)
print(total)   # 15  (wanted 80!)
fixed.py
def add_item(running, price):
    return running + price   # clean

total = 0            # local to main flow
total = add_item(total, 40)
total = add_item(total, 25)
total = add_item(total, 15)
print(total)   # 80 ✓
>> Common failures

Common scope mistakes

  1. Trying to read a local variable after the function ended → NameError.
  2. Assuming a function changed a global when it only made a same-named local copy.
  3. Reaching for global instead of passing a parameter and returning a value.
  4. Letting two parts of the program share one mutable global and overwrite each other.
  5. Expecting a loop variable to still be usable somewhere it was never in scope.
>> 11:00 – 12:00 · Lab

Today's lab — Scope Bug-Hunt

THE TWIST
It already runs

You get a short program that runs but prints the wrong total (15 instead of 80) because functions lean on a global.

YOUR JOB
Refactor the scope

Find the # BUG spots. Rewrite so each function takes parameters and returns its result — no globals.

>> End of Day 13

What you can now do

  • ✓ Tell local from global scope, and know when each variable lives and dies.
  • ✓ Spot why reading or mutating globals makes functions fragile.
  • ✓ Apply "pass it in, return it out" to write clean, self-contained functions.
01 / 12
←/→ navigate   F fullscreen   Ctrl/⌘+P save as PDF