Free: 4 trials of 20 minutes, no cardStart free

Craftstack Academy
Python

Python UnboundLocalError: cannot access local variable where it is not associated with a value

· 10 min read

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:

Terminal
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 value

UnboundLocalError: 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:

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:

Terminal (Python 3.10)
UnboundLocalError: local variable 'score' referenced before assignment

Both 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 += ..., a for 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:

python
score = 0

def add_point():
    score += 1
Terminal
UnboundLocalError: cannot access local variable 'score' where it is not associated with a value

score += 1 means score = score + 1, so it's an assignment too.

The clean fix: pass the value in, return the new value

main.py
score = 0

def add_point(score):
    return score + 1

score = add_point(score)
score = add_point(score)
print(score)
Terminal
2

The 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:

main.py
score = 0

def add_point():
    global score
    score = score + 1

add_point()
print(score)
Terminal
1

It 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:

main.py
total = 100

def show():
    print(total)
    total = 50

show()
Terminal
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 value

If 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:

main.py
def grade(points):
    if points >= 50:
        result = "pass"
    print(result)

grade(80)
grade(30)
Terminal
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 value

For 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:

python
    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:

main.py
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]))
Terminal
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 value

With 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:

main.py
def counter():
    count = 0
    def increase():
        count += 1
        return count
    return increase

c = counter()
print(c())
Terminal
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 value

Here the right keyword is nonlocal, which means "the variable of the enclosing function":

main.py
def counter():
    count = 0
    def increase():
        nonlocal count
        count += 1
        return count
    return increase

c = counter()
print(c(), c())
Terminal
1 2

You 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:

main.py
items = []

def add(item):
    items.append(item)

add("pen")
print(items)
Terminal
['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. UnboundLocalError is a special kind of NameError: 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, like math = 3 inside a function that also uses math.pi. The local name hides the module. Pick a different name.
  • TypeError: 'NoneType' object is not subscriptable: the variable has a value, but it's None. See 'NoneType' object is not subscriptable.

Wrong fixes that don't help

  • Adding global everywhere. It removes the error but turns every function into one that can secretly change shared data.
  • Moving the outside variable into the function. score = 0 inside add_point resets 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':

  1. Look at the last File line in the traceback: that's the function and the line.
  2. Search the function for balance =, balance += or for balance. If you find one, balance is local in the whole function.
  3. 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.
  4. If the only assignments are inside if or for, give it a starting value before them.
  5. Run with the input that failed, not only the one that works.

Practice

Predict what happens.

  1. count = 0, a function that does print(count) and nothing else, called once.
  2. count = 0, a function that does print(count) and then count = 1, called once.
  3. names = [], a function that does names.append("Sam"), called once, then print(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

  1. Find the function in the last File line of the traceback.
  2. Look for any assignment to the name in that function.
  3. Want the outside value? Pass it in and return the new value.
  4. Assigned only in an if or loop? Set a starting value first.
  5. 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.

1 beginner error a week

One common error, what it means and how to fix it, in a short email. Free, and you can unsubscribe in any email.

Learn by writing the code yourself.

Twenty minutes with the tutor, right in your browser. No card, nothing to install.

Start the free trial
A session: the tutor's chat on the left, the code editor with a Java program and its output on the right