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.
Your error
Check these first
- Assigning makes it local. If a function assigns to
xanywhere, everyxin that function is its own, even above the assignment. - Pass it in, return it. Give the function the value as a parameter and
returnthe new one, instead of changing an outside variable. - Every path sets it. A variable set only inside an
ifhas 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.)
count = 0
def add():
count += 1
add()
print(count)
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
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.
x = 10
def show():
print(x)
x = 20
show()
UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
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.
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
def grade(score):
result = "fail"
if score >= 50:
result = "pass"
return result
print(grade(30))
fail
Still stuck?
- In the traceback,
File "main.py", line 3says where the error happened. In the editor, click that line to go to it. - Go over the basics: Scope
- Other errors: AttributeError, FileNotFoundError, IndentationError, IndexError, KeyError, ModuleNotFoundError, NameError, RecursionError, SyntaxError, TypeError, ValueError, ZeroDivisionError