On 10/02/2012 10:03 PM, contro opinion wrote: > code1 >>>> def foo(): > ... a = 1 > ... def bar(): > ... b=2 > ... print a + b > ... bar() > ... > ... >>>> foo() > 3 > > code2 >>>> def foo(): > ... a = 1 > ... def bar(): > ... b=2 > ... a = a + b
Because your function bar() has an assignment to a, it becomes a local, and masks access to the one in the containing function. Then because when you start executing that assignment statement, a hasn't yet gotten a value, you get the error below. > ... print a > ... bar() > ... >>>> foo() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<stdin>", line 7, in foo > File "<stdin>", line 5, in bar > UnboundLocalError: local variable 'a' referenced b > > why code2 can not get output of 3? > In Python3, you can avoid the "problem" by declaring a as nonlocal. def foo(): a = 1 def bar(): nonlocal a b=2 a = a + b print (a) bar() foo() if you're stuck with Python2.x, you can use a mutable object for a, and mutate it, rather than replace it. For example, def foo(): a = [3] def bar(): b=2 a.append(b) #this mutates a, but doesn't assign it print (a) a[0] += b #likewise, for a number within the list print (a) bar() That should work in either 2.x or 3.2 -- DaveA -- http://mail.python.org/mailman/listinfo/python-list