The following function works just fine.
>>> x = 1
>>> def test():
... y = x + 1
... return y
...
>>> test()
2
However why does the following function split an error?
>>> x = 1
>>> def test2():
... x = x + 1
... return x
...
>>> test2()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in test2
UnboundLocalError: local variable 'x' referenced before assignment
Why does python creates a local variable with the value 2 instead of giving this error.