Local Variable

A local variable is a variable that exists only within a function.

x = 5

def sum(a, b):
    return a + b

In the body of sum, a and b are local variables. Outside of sum, a and b do not exist.

x is a global variable.

Shadowing

It's possible to have a local variable and a global variable with the same name.

x = 5

def display_x():
    x = 6
    print(x)

Wherever the name x appears in the body of display_x, it refers to the local variable, not the global. This is because the local variable shadows the global variable of the same name.

>>> x
5
>>> display_x()
6
>>> x
5

What makes a variable local?

A variable is local if it is assigned to within a function.

UnboundLocalError

UnboundLocalError means that your code tried to use a variable before any value was assigned to it. It's just like NameError but for local variables.