0

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.

Malachi
  • 53
  • 6
  • As demonstrated by linked duplicate, you can read a global value in your function but cannot assign a new value to it, without using global keyword. Without global keyword, python is trying to assign a value to a local variable that doesn't exist yet. – R3uben Jan 30 '21 at 13:00
  • Thanks @R3uben. I understand. – Malachi Jan 30 '21 at 13:47

0 Answers0