Two students in different classes can both be called Rohan. Inside class 10A, "Rohan" means the one in 10A; the teacher doesn't mean the Rohan in 10B. Python names work the same way. A variable called total inside a function is a different variable from a total outside it. Where a name can be seen and used is its scope, and Python variable scope follows one rule, called LEGB, to decide which total you mean.
Scope explains some of the most confusing beginner errors, such as UnboundLocalError and "my function changed the variable but nothing happened outside". This lesson covers the four scopes, the LEGB lookup order, the global and nonlocal keywords, and why you should rarely need either.
What you need first: Python functions.
Key terms
- Scope: the part of a program where a name can be used.
- Namespace: a mapping from names to values. Each scope has its own, a bit like a dictionary.
- Local variable: a variable created inside a function. It exists only while that function runs.
- Global variable: a variable created at the top level of a file (a module), outside any function.
- Enclosing scope: the scope of an outer function, as seen from a function defined inside it.
- Built-in: names Python provides everywhere, such as
print,lenandmax.
Local and global variables
A variable created inside a function is local. Code outside the function can't see it:
def make_bill():
total = 450
print("Inside:", total)
make_bill()
print("Outside:", total)
Inside: 450
NameError: name 'total' is not defined
total was created when make_bill ran and thrown away when it finished. That's a good thing: functions can use whatever names they like without clashing with the rest of your program.
A variable created at the top level is global. Functions can read it:
GST_RATE = 0.18
def with_gst(price):
return round(price * (1 + GST_RATE), 2)
print(with_gst(1000))
1180.0
GST_RATE isn't defined inside with_gst, so Python looks outside and finds the global one. Writing constants in CAPITALS is a convention that tells readers "this never changes".
Same name, different variables
city = "Pune"
def plan_trip():
city = "Goa"
print("Inside:", city)
plan_trip()
print("Outside:", city)
Inside: Goa
Outside: Pune
Assigning city = "Goa" inside the function creates a new local city. The global one is untouched. This is called shadowing: the local name hides the global one inside the function.
The LEGB rule
When Python meets a name, it searches four scopes in this order and uses the first match:
| Letter | Scope | Where it is |
|---|---|---|
| L | Local | Inside the current function |
| E | Enclosing | Inside any outer functions, from the nearest outwards |
| G | Global | The top level of the current file |
| B | Built-in | Names Python provides, like len and print |
If the name isn't in any of them, you get a NameError.
Here's all four in one example:
x = "global x"
def outer():
x = "enclosing x"
def inner():
x = "local x"
print(x)
inner()
outer()
local x
Delete the line x = "local x" and inner prints enclosing x. Delete the one in outer too and it prints global x. Python always stops at the nearest match.
Shadowing a built-in
Because built-ins are searched last, your own names win. This causes a classic bug:
marks = [72, 88, 95]
sum = 0
for m in marks:
sum += m
print(sum)
print(sum([1, 2, 3]))
255
TypeError: 'int' object is not callable
Naming a variable sum hid the built-in sum function for the rest of the file. The same happens with list, str, max, input and id. Use names like total instead. If it happens in a notebook, restart the kernel or run del sum.
Why you get UnboundLocalError
This one confuses almost everyone the first time:
count = 0
def add_visit():
count = count + 1
return count
add_visit()
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
You'd expect Python to read the global count, add 1, and store the result. But Python decides a name's scope for the whole function before it runs any of it. Because count is assigned somewhere in the function, it's local everywhere in that function, including on the right of the =. And that local count has no value yet. (Older Python versions word the message as local variable 'count' referenced before assignment.)
The best fix is to pass the value in and return the new one:
def add_visit(count):
return count + 1
count = 0
count = add_visit(count)
count = add_visit(count)
print(count)
2
The global keyword
global tells Python "this name inside the function means the global one", so you can assign to it:
count = 0
def add_visit():
global count
count += 1
add_visit()
add_visit()
print(count)
2
It works, but use it rarely. When many functions change global variables, you can't tell which one changed a value without reading the whole program, and functions become hard to test on their own. Passing values in and returning results, as in the previous section, is almost always clearer. Our opinion: in your first year of Python, treat global as a sign that the design needs another look.
Changing versus reassigning
You don't need global to change a mutable object such as a list or dictionary. You only need it to reassign the name:
cart = []
def add_item(item):
cart.append(item) # changes the list: no global needed
add_item("milk")
add_item("bread")
print(cart)
['milk', 'bread']
cart.append(...) doesn't assign to cart; it changes the list that cart points to. Python finds cart in the global scope with LEGB and calls its method. Writing cart = cart + ["eggs"] inside the function, on the other hand, would raise UnboundLocalError.
The nonlocal keyword
nonlocal is like global, but for the enclosing function's variable. It's used when an inner function needs to update a value in its outer function:
def make_counter():
count = 0
def increment():
nonlocal count
count += 1
return count
return increment
counter = make_counter()
print(counter(), counter(), counter())
1 2 3
increment remembers count even after make_counter has finished. A function that remembers variables from its enclosing scope is called a closure. Closures are the basis of decorators, which you'll meet in the advanced module.
Scope in loops, if blocks and comprehensions
Python has no block scope. A variable created inside a for loop or an if block is still there afterwards:
for i in range(3):
last_seen = i
print(i, last_seen)
if True:
message = "created inside if"
print(message)
2 2
created inside if
This surprises people coming from C, Java or JavaScript, where blocks have their own scope. Only functions, classes and modules create new scopes in Python. Comprehensions are the one small exception: their loop variable stays inside them.
squares = [n * n for n in range(4)]
print(squares)
print("n" in dir())
[0, 1, 4, 9]
False
Seeing what's in scope
locals() and globals() return the current namespaces as dictionaries. They're useful when you're confused about what exists:
rate = 0.18
def show():
price = 100
print(locals())
print("rate" in globals())
show()
{'price': 100}
True
Where scope matters in real work
- Jupyter notebooks: every cell shares one global scope, so a variable from a cell you ran an hour ago can silently change results. "Restart and run all" before trusting a notebook's output.
- Data pipelines: functions that take inputs and return outputs, with no global state, are easy to test and rerun.
- Web apps: global variables are shared between all users of a Flask or Django server, so storing a user's data in one leaks it to others.
Common mistakes
- Using a variable after the function that made it has finished. Return it instead.
- Naming variables
sum,list,maxorinput, which hides the built-ins. - Assigning to a global inside a function without realising it creates a local, which leads to
UnboundLocalErroror changes that "vanish". - Using
globaleverywhere to get values out of functions. Usereturn.
Practice
- What does this print?
x = 10
def f():
x = 20
return x
print(f(), x)
Show the answer
20 10
The x = 20 inside f creates a local x. The global x stays 10.
- Why does this fail, and how do you fix it without
global?
score = 50
def bonus():
score = score + 10
bonus()
Show the answer
score is assigned inside bonus, so it's local throughout the function, and score + 10 reads a local that has no value yet: UnboundLocalError. Pass it in and return it:
def bonus(score):
return score + 10
score = 50
score = bonus(score)
print(score)
60
- What does this print?
items = [1, 2]
def change():
items.append(3)
change()
print(items)
Show the answer
[1, 2, 3]
append changes the existing list. No assignment to items happens, so no global is needed.
- Write
make_multiplier(n)that returns a function which multiplies its argument byn. Use it to makedoubleandtriple.
Show the answer
The inner function reads n from the enclosing scope. It doesn't assign to it, so nonlocal isn't needed:
def make_multiplier(n):
def multiply(x):
return x * n
return multiply
double = make_multiplier(2)
triple = make_multiplier(3)
print(double(5), triple(5))
10 15
- Use
nonlocalto writemake_bank_account(balance)that returns adeposit(amount)function, which adds to the balance and returns the new balance.
Show the answer
def make_bank_account(balance):
def deposit(amount):
nonlocal balance
balance += amount
return balance
return deposit
deposit = make_bank_account(1000)
print(deposit(500), deposit(250))
1500 1750
Without nonlocal, balance += amount would raise UnboundLocalError, for the same reason as question 2.
Interview questions
What is the LEGB rule?
It's the order Python searches for a name: Local (current function), Enclosing (outer functions), Global (module level), then Built-in. The first match wins; if none matches, Python raises NameError.
What is the difference between global and nonlocal?
global x makes x in a function refer to the module-level variable. nonlocal x makes it refer to the variable in the nearest enclosing function. Both are needed only to reassign the name, not to read it or change a mutable object.
Why does Python raise UnboundLocalError instead of reading the global variable?
Python decides at compile time that any name assigned in a function is local to the whole function. Reading it before the assignment then refers to a local that has no value, so Python raises UnboundLocalError rather than silently using the global.
Key takeaways
- Variables made inside a function are local and disappear when it ends.
- Python looks names up in order: Local, Enclosing, Global, Built-in.
- Assigning to a name anywhere in a function makes it local for the whole function.
globalandnonlocallet you reassign outer names, but passing values in and returning them is usually better.- Loops and
ifblocks don't create a new scope; functions do.
Frequently asked questions
Are global variables bad in Python?
Global constants, like GST_RATE = 0.18, are fine and common. Global variables that many functions change are what cause bugs, because any function could have changed the value.
Can a function access a variable defined after it?
Yes, as long as the variable exists by the time the function is called. Python looks the name up when the line runs, not when the function is defined.
Do Python if statements create a new scope?
No. Only functions, classes, modules and comprehensions create a new scope. Variables made inside if, for, while and with blocks are visible after the block.
What to learn next
- Write functions that call themselves in recursion in Python.
- See closures in action with lambda, map, filter and sorted.
- Revise the basics in Python functions.