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.
A variable created inside a function exists only while that function runs. The moment the function returns, the name vanishes.
def greet():
message = "hi there" # local to greet()
print(message)
greet() # hi there
print(message) # NameError: not defined
message only exists inside greet(). Outside, Python has never heard of it.
The same name in two functions is two different variables. They never collide — each lives in its own room.
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.
A variable defined at the top level of your file — not inside any function — is global. Functions are allowed to read it.
TAX_RATE = 0.05 # global, top level
def with_tax(price):
return price * (1 + TAX_RATE)
print(with_tax(80)) # 84.0
TAX_RATE is a fine global. The trouble starts when globals change.
A function that reads a changing global gives different answers depending on what happened earlier. You can't trust it just by reading it.
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!
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.
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.
Whatever a function needs, hand it in as a parameter. Whatever it produces, hand back with return. No reaching out to globals.
total = total + price
# reads & writes a global
return running + price
# in via params, out via return
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!)
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 ✓
NameError.global instead of passing a parameter and returning a value.You get a short program that runs but prints the wrong total (15 instead of 80) because functions lean on a global.
Find the # BUG spots. Rewrite so each function takes parameters and returns its result — no globals.
students/<your-username>/D13_scope_bughunt.py. Full brief in lab/module_1_foundations/D13_scope_bughunt/problem.md. PR before 12:00.