You keep a score in a variable and write a small function to add a point. The variable clearly exists, but Python says it doesn't have a value:
Traceback (most recent call last):
File "main.py", line 6, in <module>
add_point()
~~~~~~~~~^^
File "main.py", line 4, in add_point
score = score + 1
^^^^^
UnboundLocalError: cannot access local variable 'score' where it is not associated with a valueUnboundLocalError: cannot access local variable 'score' where it is not associated with a value means that inside a function, Python treats score as a local variable, one that belongs only to that function, and you read it before the function gave it a value. The score outside the function is ignored. It feels like a bug in Python, but it follows one simple rule, and once you know the rule, the fix is quick. This article explains the rule, the four common situations and the clean fixes.
Try it yourself
Save this as main.py and run python main.py:
score = 0
def add_point():
score = score + 1
add_point()
print(score)You'll get the error above. Note the traceback has two parts: the first shows where you called the function (line 6), the last shows where it actually failed (line 4, inside add_point).
The same error in older Python versions
Python 3.11 changed the wording. In Python 3.8, 3.9 and 3.10, the same program says:
UnboundLocalError: local variable 'score' referenced before assignmentBoth messages mean exactly the same thing. "Referenced before assignment" is the older, shorter way of saying "you read it before it had a value". If you search for the error, you'll find answers with either wording.
The rule behind the error
When Python reads a function, it looks at every variable name in it and decides, once, for the whole function:
- If the function assigns to a name anywhere (
score = ...,score += ..., afor score in ...loop), that name is local to the function in every line of it. - If the function only reads a name, Python looks for it outside: in the file, then among the built-ins.
In add_point, the line score = score + 1 assigns to score. So score is local everywhere in the function, including the right-hand side of that same line. When Python evaluates score + 1, the local score has no value yet, and you get the error. The score = 0 at the top of the file is a different variable, which this function never looks at.
That's what "not associated with a value" means: the name is known, as a local variable, but nothing has been stored in it yet.
Cause 1: changing a variable from outside the function
The example above, and its short form:
score = 0
def add_point():
score += 1UnboundLocalError: cannot access local variable 'score' where it is not associated with a valuescore += 1 means score = score + 1, so it's an assignment too.
The clean fix: pass the value in, return the new value
score = 0
def add_point(score):
return score + 1
score = add_point(score)
score = add_point(score)
print(score)2The function gets the current value as a parameter, returns the new value, and the caller stores it. Nothing is hidden: you can see exactly where score changes. This is the fix to prefer, especially while you're learning.
The quick fix: global
You can tell Python that the name refers to the variable outside:
score = 0
def add_point():
global score
score = score + 1
add_point()
print(score)1It works, but use it sparingly. With global, any function can change the variable, and in a bigger program it gets hard to tell which one did. The parameter-and-return version scales better.
Cause 2: reading a variable before you assign it in the same function
Here, the function only seems to read total first. But it also assigns to it a line later, and that's enough to make it local everywhere:
total = 100
def show():
print(total)
total = 50
show()Traceback (most recent call last):
File "main.py", line 7, in <module>
show()
~~~~^^
File "main.py", line 4, in show
print(total)
^^^^^
UnboundLocalError: cannot access local variable 'total' where it is not associated with a valueIf you meant two different variables, give the local one a different name, like new_total. If you meant the outer one, pass it in as a parameter.
Cause 3: a variable set only inside an if
This version has nothing to do with outside variables. The local variable is assigned in one branch only:
def grade(points):
if points >= 50:
result = "pass"
print(result)
grade(80)
grade(30)pass
Traceback (most recent call last):
File "main.py", line 7, in <module>
grade(30)
~~~~~^^^^
File "main.py", line 4, in grade
print(result)
^^^^^^
UnboundLocalError: cannot access local variable 'result' where it is not associated with a valueFor 80, it works. For 30, the if is false, result is never assigned, and Python can't print it. That's why this error often appears only for some inputs. Make sure every path assigns the variable, for example with an else:
if points >= 50:
result = "pass"
else:
result = "fail"Or give it a starting value before the if.
The loop version
The same happens with a value found in a loop:
def find_first_even(numbers):
for n in numbers:
if n % 2 == 0:
found = n
break
return found
print(find_first_even([1, 4, 5]))
print(find_first_even([1, 3]))4
Traceback (most recent call last):
File "main.py", line 9, in <module>
print(find_first_even([1, 3]))
~~~~~~~~~~~~~~~^^^^^^^^
File "main.py", line 6, in find_first_even
return found
^^^^^
UnboundLocalError: cannot access local variable 'found' where it is not associated with a valueWith no even number, found is never set. Start with found = None before the loop, and let the caller check for None.
Cause 4: a function inside a function
When you write a function inside another function, the inner one has the same rule. Changing a variable of the outer function gives the same error:
def counter():
count = 0
def increase():
count += 1
return count
return increase
c = counter()
print(c())Traceback (most recent call last):
File "main.py", line 9, in <module>
print(c())
~^^
File "main.py", line 4, in increase
count += 1
^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a valueHere the right keyword is nonlocal, which means "the variable of the enclosing function":
def counter():
count = 0
def increase():
nonlocal count
count += 1
return count
return increase
c = counter()
print(c(), c())1 2You won't need this in your first programs, but it's good to recognise.
Why changing a list doesn't cause it
This works without global, which surprises many people:
items = []
def add(item):
items.append(item)
add("pen")
print(items)['pen']items.append(...) doesn't assign to the name items. It changes the list that items refers to. Only assignment (=, += and similar) makes a name local. That's the whole rule again, seen from the other side.
Errors that look alike
NameError: name 'x' is not defined: the name doesn't exist anywhere.UnboundLocalErroris a special kind ofNameError: the name exists as a local variable, but has no value yet. See NameError: name is not defined.AttributeError: 'int' object has no attribute 'pi': a local variable with the same name as a module, likemath = 3inside a function that also usesmath.pi. The local name hides the module. Pick a different name.TypeError: 'NoneType' object is not subscriptable: the variable has a value, but it'sNone. See 'NoneType' object is not subscriptable.
Wrong fixes that don't help
- Adding
globaleverywhere. It removes the error but turns every function into one that can secretly change shared data. - Moving the outside variable into the function.
score = 0insideadd_pointresets the score to zero on every call. - Wrapping it in
try/except. The function still doesn't do what you meant.
A debugging walkthrough
A function fails with cannot access local variable 'balance':
- Look at the last
Fileline in the traceback: that's the function and the line. - Search the function for
balance =,balance +=orfor balance. If you find one,balanceis local in the whole function. - Decide what you meant. Use the outside value? Pass it as a parameter and return the new one. A new local value? Give it its own name.
- If the only assignments are inside
iforfor, give it a starting value before them. - Run with the input that failed, not only the one that works.
Practice
Predict what happens.
count = 0, a function that doesprint(count)and nothing else, called once.count = 0, a function that doesprint(count)and thencount = 1, called once.names = [], a function that doesnames.append("Sam"), called once, thenprint(names).
Answers. (1) Prints 0: the function only reads count, so it finds the outer one. (2) UnboundLocalError: the later assignment makes count local in the whole function. (3) Prints ['Sam']: append changes the list without assigning to the name.
Frequently asked questions
What does "cannot access local variable where it is not associated with a value" mean?
Inside a function, a variable is local because the function assigns to it somewhere, and you read it before that assignment happened. Python 3.11 and later use this wording.
Is "local variable referenced before assignment" the same error?
Yes. It's the wording in Python 3.10 and earlier.
Should I use global to fix it?
It works, but passing the value as a parameter and returning the result is clearer and safer. Use global only for real, shared settings.
Why can I change a list inside a function but not a number?
Changing a list with append doesn't assign to its name. number += 1 does, and assignment is what makes a name local.
Why does it work for some inputs and fail for others?
The variable is assigned only inside an if or a loop that doesn't always run. Give it a value before the if or loop.
A quick checklist
- Find the function in the last
Fileline of the traceback. - Look for any assignment to the name in that function.
- Want the outside value? Pass it in and return the new value.
- Assigned only in an
ifor loop? Set a starting value first. - A function inside a function? Use
nonlocal.
For a method that works on any error, read how to read an error message. The Python documentation covers this rule in Python Scopes and Namespaces and in its programming FAQ.
