UnboundLocalError: local variable referenced before assignment

Hi everyone,

This is a question I had when I was doing Jupyter Notebook practice.
First, I defined the function get_y() and tested it:

def get_y(m, b, x):
    return m*x + b

print(get_y(1, 0, 7) == 7)
print(get_y(5, 10, 3) == 25)

Then I wrote another function:

def calculate_error(m, b, point):
    x_point = point[0]
    y_point = point[1]
    get_y = get_y(m, b, x_point)
    return abs(get_y - y_point)

When I run the testing codes:

#this is a line that looks like y = x, so (3, 3) should lie on it. thus, error should be 0:
print(calculate_error(1, 0, (3, 3)))
#the point (3, 4) should be 1 unit away from the line y = x:
print(calculate_error(1, 0, (3, 4)))
#the point (3, 3) should be 1 unit away from the line y = x - 1:
print(calculate_error(1, -1, (3, 3)))
#the point (3, 3) should be 5 units away from the line y = -x + 1:
print(calculate_error(-1, 1, (3, 3)))

The error shows:

UnboundLocalError: local variable ‘get_y’ referenced before assignment

I tried to fix it by replacing “get_y” variable to “y”, and it worked. I googled this error but I am still a little confused:
I didn’t find my “get_y” variable referenced before. Is it because there is a conflict between variable name and the function name?


Where is it referenced? Where is it assigned? Use the trace back to help discover one of the endpoints, then trace back to the other.

An UnboundLocalError is raised when a local variable is referenced before it has been assigned. In most cases this will occur when trying to modify a local variable before it is actually assigned within the local scope. Python doesn’t have variable declarations, so it has to figure out the scope of variables itself. It does so by a simple rule: If there is an assignment to a variable inside a function, that variable is considered local.

Python has lexical scoping by default, which means that although an enclosed scope can access values in its enclosing scope, it cannot modify them (unless they’re declared global with the global keyword). A closure binds values in the enclosing environment to names in the local environment. The local environment can then use the bound value, and even reassign that name to something else, but it can’t modify the binding in the enclosing environment. UnboundLocalError happend because when python sees an assignment inside a function then it considers that variable as local variable and will not fetch its value from enclosing or global scope when we execute the function. However, to modify a global variable inside a function, you must use the global keyword.