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)
```