All Python errors
UnboundLocalError in Python: cannot access local variable
UnboundLocalError means a function reads a local variable that has no value yet. A name assigned anywhere inside a function is local to the whole function, so pass the outer value as an argument and return the new one.
Code with the error
visits = 10
def add_visit():
visits = visits + 1
return visits
print(add_visit())
Error message (Python 3.12, last line)
Corrected code
def add_visit(visits):
return visits + 1
visits = 10
visits = add_visit(visits)
print(visits)
Output
11
Common causes
- A function changes an outer variable with x = x + 1 or x += 1.
- The variable gets a value only inside an if branch that did not run.
- The variable is assigned inside a loop that ran zero times.
- The line that reads the variable stands above the line that assigns it.
Practise in the course
Lesson: FunctionsFrequently asked questions
Why can the function not see the variable defined above it?
Because the function also assigns that name. Python then treats it as a new local variable everywhere in the function.
What about the global keyword?
It lets a function change a module variable, but passing arguments and returning values is easier to follow and works in the editor on this site.