'x' referenced before assignment


#1

Can someone explain why declaring a variable outside of a function returns the error:UnboundLocalError: local variable 'x' referenced before assignment?
Example:

x = 0
def digit_sum(n):
    n = str(n)
    for i in n:
        i = int(i)
        x = x + i
    return x
print digit_sum(123)

while does not produce an error? What difference does it make where the variable is declared?

def digit_sum(n):
x = 0
    n = str(n)
    for i in n:
        i = int(i)
        x = x + i
    return x
print digit_sum(123)

#2

Because of local and a global variables. you can only access local variable within the function. If you want make x global variable so that you can use it inside and outside function you have to type "global x" and set the value inside the function.