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

8
  • 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. Commented May 25, 2014 at 6: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. Commented May 25, 2014 at 6: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. Commented May 25, 2014 at 6:07
  • 1
    @AshishJain as the linked question says, doing x = anywhere in a function makes x be a local. Commented May 25, 2014 at 6: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. Commented May 25, 2014 at 6:34

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.