Code with the error

visits = 10

def add_visit():
    visits = visits + 1
    return visits

print(add_visit())

Error message (Python 3.12, last line)

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

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

Frequently 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.