1

Possible Duplicate:
Python variable scope question
Python nested function scopes

I'm confused about the following piece of code

def func():
    a=10
    def func2():
        print a
        a=20
    func2()
    print a

func()

In python 2.7, when running the above code, python will give an error, UnboundLocalError, complaining in func2, when print a, 'a' is referenced before assignment

However, if I comment a=20 in func2, everything goes well. Python will print two lines of 10; i.e, the following code is correct.

def func():
    a=10
    def func2():
        print a

    func2()
    print a

func()

Why? Since in other languages, like c/c++

{
    a=10
    {
        cout<<a<<endl //will give 10
        a=20          //here is another a
        cout<<a<<endl //here will give 20
    }
}

local and outer variables can be distinguished very clearly.

Community
  • 1
  • 1
Junjie
  • 469
  • 1
  • 4
  • 14
  • 2
    in python, everything you assign to is assumed to be local. – georg Aug 21 '12 at 09:36
  • My guees would be that the scope of func2 is independent of the scope of func. You basically just defining a function func2 which is just visible in the scope of func. That doesn implicies that func2 sees the local variables in func. – Sebastian Hoffmann Aug 21 '12 at 09:38
  • sorry, I didn't find these duplicates. should I delete my questions? – Junjie Aug 21 '12 at 09:41

1 Answers1

1

By adding the line a=20, Python analyzes the code and sees that a is also used as a local variable name. In that case you are trying to print the value of a variable that has not yet been defined (in func2).

Without that line, Python will use the value of a from the scope of func (which is still valid inside func2). You are correct that this is different from your example in C/C++.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180