Well I am trying to access a variable declared outside of a function. Then whenever I am changing the variable value inside of the function I see an error message...
UnboundLocalError: Local variable 'x' referenced before assignment
Here is the module...
x = 5
def fun():
print 'x is', x
x = 10
print 'x is now changed to', x
fun()
It seems Python assuming the x declared inside of function is different than the x declared outside of the function. Also when I comment out line 5 the program runs without error.
Is this anything relevant to any rule like Python functions will give priority to the variables declared inside of it and if I want to do something like this program then I have to use global
statement to achieve the goal?
Answer: Ok I think I sort out the point. Thanks to @unixer for providing me the link - Python documentation on the topic. Actually when we declare a variable in any scope the variable becomes local to that particular scope and it shadows any similarly named variable outside of its scope unless the variable gets another new assignment to it in local or outer scope. In my case...
- When I first assigned value to
x
outside of the function,x
became local variable to that particular scope. - And then when I fetched value of
x
inside of the functionfun
compiler printed value ofx
as declared in outer scope of the function. - And again when I assigned new value to
x
(on line 5) compiler assigned new value tox
. BUT this time it thought I did a mistake as I am trying to printx
(on line 4) before assigning a value to it.
Point 3 is same as...
print 'x is', x
x = 5
Compiler will raise same error as it sees I am trying to print value of x before assigning any value to it.