0

I know it is a basic question but i don't know reason of this question. I am confused a bit, why global variable is act as local variable in test method.

x=1
def test():
    print x
    x=2
    print x

print x
test()
print x

It is giving the exception which is like this.

UnboundLocalError: local variable 'x' referenced before assignment

Anyone let me know why it is giving this error.

Thanks

Ashish Jain
  • 760
  • 1
  • 8
  • 23
  • 3
    For the love of all that is good, ***please*** take the two seconds to *search* before asking such a basic question. [Google gives many good results](https://www.google.com/search?q=python+global). – Jonathon Reinhart May 25 '14 at 06:00
  • 1
    "but i don't know reason of this question". The reason that your asking this question is because you want an answer to it. – Scorpion_God May 25 '14 at 06:03
  • I know i can search but i didn't get my solution. i m asking only if x=1 is a global variable then why i am getting exception and why i use `global x` term for x in method. already x is global variable. – Ashish Jain May 25 '14 at 06:07
  • 1
    @AshishJain as the linked question says, doing `x =` anywhere in a function makes `x` be a local. – Eevee May 25 '14 at 06:28
  • It means, In function if i use any global variable then this function will treat as local variable until we define x as `global`. Is it correct @Eevee. – Ashish Jain May 25 '14 at 06:34
  • @Eevee Please confirm my statement. – Ashish Jain May 25 '14 at 07:10
  • @AshishJain You can [confirm it on your own](https://docs.python.org/2/reference/simple_stmts.html#assignment-statements): "If the name [to be assigned to] does not occur in a `global` statement in the current code block: the name is bound to the object in the current local namespace." In short, if you do `x = ...`, `x += ...` or whatever in a function, `x` is local unless you bind it to the global name `x` with `global x`. – glglgl May 25 '14 at 07:39
  • you can read from a global `x` all you like, but as soon as you say `x =` in a function, `x` is defined as a local and shadows the global. – Eevee May 25 '14 at 18:50

0 Answers0