How Do You Troubleshoot a Python Error “UnboundLocalError: local variable ‘x’ referenced before assignment”?

Problem scenario
You run a Python program but you get this error: "UnboundLocalError: local variable 'x' referenced before assignment"

Solution
Root Cause

You have a function in Python and it refers to a previously assigned variable.  This variable was not passed as a parameter.

Procedures
You need to redeclare (but not necessarily reassign) the variable as a "global".  This way the value is preserved.

Here is an example of redeclaring a variable as global inside a function that will eliminate the error message:

x = 5
def coolfunction(a, b)
  global x
  ...

Leave a comment

Your email address will not be published.