Python errors / UnboundLocalError

UnboundLocalError: cannot access local variable

A function used a variable before giving it a value. Assigning to a name anywhere in a function makes it that function's own variable.

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

Check these first

  1. Assigning makes it local. If a function assigns to x anywhere, every x in that function is its own, even above the assignment.
  2. Pass it in, return it. Give the function the value as a parameter and return the new one, instead of changing an outside variable.
  3. Every path sets it. A variable set only inside an if has no value when the condition is false.

Causes and fixes

1 Changing an outside variable

count += 1 assigns to count, so inside the function count is a new, empty variable. Pass the value in and return the new one. (global count also works, but makes the code harder to follow.)

Broken
count = 0

def add():
    count += 1

add()
print(count)
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Fixed
count = 0

def add(count):
    return count + 1

count = add(count)
print(count)
1

2 The same name assigned later

Because the function assigns to x further down, the x it prints is its own, and it has no value yet. Use another name for the function's own variable.

Broken
x = 10

def show():
    print(x)
    x = 20

show()
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
Fixed
x = 10

def show():
    print(x)
    y = 20
    print(y)

show()
10
20

3 Set only inside an if

When the condition is false, the variable is never set. Give it a value before the if, or set it in an else.

Broken
def grade(score):
    if score >= 50:
        result = "pass"
    return result

print(grade(30))
UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
Fixed
def grade(score):
    result = "fail"
    if score >= 50:
        result = "pass"
    return result

print(grade(30))
fail

Still stuck?