Variable Scope
A variable's scope is the part of a program where that variable can be seen and used. Variables created inside a function are local to it, while variables created at the top level of a file are global. Understanding scope prevents some of the most confusing bugs beginners meet.
Local variables
A variable assigned inside a function, including its parameters, exists only while that function runs. Code outside the function can't see it.
county = "Nakuru" # global
def show_town():
town = "Naivasha" # local to show_town
print(town, "is in", county)
show_town()
print(county)
Adding print(town) at the bottom of this program would raise a NameError, because town stopped existing when show_town() finished. This is a good thing: each function has its own private workspace, so variables in different functions can't clash.
Global variables
A variable created outside all functions is global. Functions can read it, as show_town() read county above.
Same name, different variables
If a function assigns to a name that also exists globally, it creates a new local variable that hides (or "shadows") the global one. The global is untouched.
score = 10
def play():
score = 99 # a new local variable
print("Inside:", score)
play()
print("Outside:", score)
The UnboundLocalError trap
Python decides whether a name is local by looking at the whole function before running it. If the function assigns to a name anywhere, that name is local throughout the function, even on lines before the assignment.
count = 0
def increase():
count = count + 1 # count is local here, but has no value yet
print(count)
increase()
Because increase() assigns to count, Python treats count as local. Reading it on the right-hand side happens before any local value exists, so the program fails.
The global keyword
To change a global variable from inside a function, declare it with global first.
count = 0
def increase():
global count
count += 1
increase()
increase()
print(count)
Use global sparingly. When many functions change the same global variable, it becomes hard to tell which one caused a wrong value. The cleaner approach is usually to pass values in as arguments and send results back with return.
def increase(count):
return count + 1
count = 0
count = increase(count)
count = increase(count)
print(count)
This version does the same job, but the function depends only on its input, which makes it easier to test and reuse.
Changing vs. reassigning a mutable global
There's an important difference between reassigning a name and changing the object it refers to. Calling a method such as append() on a global list doesn't assign to the name, so no global statement is needed.
attendance = []
def mark_present(name):
attendance.append(name) # changes the list; no assignment to the name
mark_present("Zawadi")
mark_present("Kevin")
print(attendance)
Nested functions and nonlocal
A function can be defined inside another function. The inner function can read the outer function's variables. To change one, declare it nonlocal, the nested-function cousin of global.
def make_counter():
count = 0
def step():
nonlocal count
count += 1
return count
return step # return the inner function itself
counter = make_counter()
print(counter())
print(counter())
print(counter())
The inner function remembers count even after make_counter() has finished. This is called a closure, and it is the idea behind decorators.
The LEGB rule
When you use a name, Python searches four scopes in order and uses the first match:
- Local: inside the current function.
- Enclosing: inside any outer functions (for nested functions).
- Global: the top level of the file.
- Built-in: Python's own names, such as
print,lenandlist.
list hides the built-in one.Because the global scope is searched before built-ins, naming a variable list, sum or input hides the real function for the rest of the file. After list = ["a", "b"], calling list("xyz") fails with TypeError: 'list' object is not callable. Choose names like names or total instead.
Key points
- Variables assigned inside a function are local and disappear when it returns.
- Functions can read globals, but assigning to a name makes it local for the whole function.
globalandnonlocallet you reassign outer variables; prefer parameters and return values.- Calling methods on a mutable global (like
append()) needs no declaration. - Python looks names up in the order Local, Enclosing, Global, Built-in (LEGB).
Tip: use the ← and → keys to move between pages.
