Can local function access local variables in main program?

Sullivan WxPyQtKinter sullivanz.pku at gmail.com
Sat Nov 3 03:18:17 EDT 2007


I am confused by the following program:

def f():
    print x
x=12345
f()

result is:
>>>
12345

however:
def f():
    print x
    x=0

x=12345
f()

result is:
Traceback (most recent call last):
  File "...\test.py", line 5, in ?
    f()
  File "...\test.py", line 2, in f
    print x
UnboundLocalError: local variable 'x' referenced before assignment


I am using
Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)]
on win32
I also tested it on python 2.5, which gives the same result.




More information about the Python-list mailing list