Sub topic 7
Where function variables live: local scope
This chapter assumes you can define and call a function with def, pass arguments, and use return. It also assumes you know basic lists, tuples and dictionaries. Here you learn which variables a function can see and which ones disappear when it ends.
The working model
Python gives every function call its own local scope. This is a private namespace that holds the function's parameters and any variable you assign inside the body. When the call returns, that namespace is discarded.
def total_price(price, tax_rate):
tax = price * tax_rate
return price + tax
print(total_price(100, 0.2)) # 120.0
print(tax) # NameError: name 'tax' is not definedThe names price, tax_rate and tax exist only while total_price runs. The last line fails because tax is not defined outside the function.
Each call gets a fresh namespace. Two calls never share local variables, and a call cannot see variables from an earlier call.
Reading outside names
A function can read a variable defined at module level, called a global variable. Python looks in the local scope first, then the global scope, then the built-ins such as len and print.
TAX_RATE = 0.2
def add_tax(price):
return price * (1 + TAX_RATE)
print(add_tax(50)) # 60.0Reading a global is fine for constants. For anything that changes, pass the value in as a parameter. The function then depends only on its inputs, which makes it easier to test and reason about.
Assignment creates a local name
The key rule is that assigning to a name anywhere in a function body makes that name local for the whole body. Python decides this when it compiles the function, before any line runs.
count = 10
def increment():
count = count + 1 # UnboundLocalError
return count
increment()Because count is assigned in the body, Python treats it as local. The right side then tries to read a local count that has no value yet, so it raises UnboundLocalError.
A similar trap is shadowing. If you assign a name that already exists globally, you create a new local variable and leave the global untouched.
level = "global"
def change():
level = "local"
return level
print(change()) # local
print(level) # globalThe global keyword
The global statement tells Python that a name inside the function refers to the module-level variable.
count = 0
def increment():
global count
count += 1
increment()
increment()
print(count) # 2This works, but it hides a dependency and makes the function change state that callers cannot see in its signature. Prefer passing a value in and returning the new value:
def increment(count):
return count + 1
count = 0
count = increment(count)
count = increment(count)
print(count) # 2Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `NameError` after calling a function | The variable was local to the function | Return the value and store it |
| `UnboundLocalError` | You assign to a name and read it first in the same function | Pass it as a parameter, or use a different local name |
| Global value unchanged after a call | Assignment created a local variable that shadowed it | Return the new value instead |
Exercise
What does this code print, and why? x = 5 def f(): x = x * 2 return x print(f())
Show answer
It raises UnboundLocalError. Because the body assigns to x, Python treats x as local for the whole function. The expression x 2 reads that local x before it has a value. The global x = 5 is never used. To fix it, accept x as a parameter (def f(x)) or use a different local name such as y = x 2.
Exercise
Rewrite this function so it does not use global and still keeps a running total. total = 0 def add(n): global total total += n
Show answer
Pass the current total in and return the new one: def add(total, n): return total + n total = 0 total = add(total, 5) total = add(total, 3) print(total) # 8