So here is the code that uses x
inside a function.
x = 1
def f():
y = x
x = 2
return x + y
print x
print f()
print x
but python is not going to look up the variable out of function scope , and it results in UnboundLocalError: local variable 'x' referenced before assignment
. I am not trying to modify the value of global variable , i just want to use it when i do y=x
.
On the other hand if i just use it in return statment , it works as expected:
x = 1
def f():
return x
print x
print f()
Can some one explain it why?