UnboundLocalError 🐍 Python

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

A function assigns to a variable somewhere, which makes it local everywhere in that function — so reading it before the assignment fails.

Seen on: Python

Meaning

Python decides scope at compile time. If a function contains x = ..., every x in that function is local, even before the assignment. Modifying a module-level counter inside a function is the classic case.

Common causes

  • Incrementing a global inside a function (count += 1)
  • Variable assigned only in one branch
  • Assigned in try but used in except/finally

⚡ Quick fix

  1. Pass values in and return results instead of using globals
  2. Use global/nonlocal deliberately
  3. Initialise before branches

Detailed fix by platform

Python

  1. python
    def increment():
        global counter
        counter += 1

How to diagnose

  1. Assignment — Where is it assigned in the function?
  2. Read — Is it read before that?

🧠 Still stuck? Analyze your error

Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.