1

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...

  1. When I first assigned value to x outside of the function, x became local variable to that particular scope.
  2. And then when I fetched value of x inside of the function fun compiler printed value of x as declared in outer scope of the function.
  3. And again when I assigned new value to x(on line 5) compiler assigned new value to x. BUT this time it thought I did a mistake as I am trying to print x (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.

Hellboy
  • 25
  • 5
  • have a look here: https://docs.python.org/2/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value – Ammar Feb 14 '15 at 15:15
  • Binding to a name in the function means it is deemed local. You need to override that explicitly by using the `global` keyword. – Martijn Pieters Feb 14 '15 at 15:17

0 Answers0