[EMAIL PROTECTED] wrote: > On Feb 19, 11:09 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote: >> On 19 Feb 2007 09:04:19 -0800, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> >> wrote: >> >> >Hi, >> >> >I have the following code: >> >> >colorIndex = 0; >> >> >def test(): >> > print colorIndex; >> >> >This won't work. >> >> Are you sure? >> >> [EMAIL PROTECTED]:~$ cat foo.py >> colorIndex = 0 >> >> def test(): >> print colorIndex >> >> test() >> [EMAIL PROTECTED]:~$ python foo.py >> 0 >> [EMAIL PROTECTED]:~$ >> >> The global keyword lets you rebind a variable from the module scope. It >> doesn't have much to do with accessing the current value of a variable. >> >> Jean-Paul > > Thanks. Then I don't understand why I get this error in line 98: > > Traceback (most recent call last): > File "./gensvg.py", line 109, in ? > outdata, minX, minY, maxX, maxY = getText(data); > File "./gensvg.py", line 98, in getText > print colorIndex; > UnboundLocalError: local variable 'colorIndex' referenced before > assignment
When there is an assignment python assumes that the variable is in the local scope (unless you explicitly declare it as global): >>> v = 42 >>> def f(): ... print v ... >>> f() 42 >>> def g(): ... print v ... v = "won't get here anyway" ... >>> g() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in g UnboundLocalError: local variable 'v' referenced before assignment >>> def h(): ... global v ... print v ... v = "for all the world to see" ... >>> h() 42 >>> v 'for all the world to see' Peter -- http://mail.python.org/mailman/listinfo/python-list