Declare a variable global

Jean-Paul Calderone exarkun at divmod.com
Mon Feb 19 12:09:04 EST 2007



On 19 Feb 2007 09:04:19 -0800, "yinglcs at gmail.com" <yinglcs at gmail.com> wrote:
>Hi,
>
>I have the following code:
>
>colorIndex = 0;
>
>def test():
>     print colorIndex;
>
>This won't work.

Are you sure?

    exarkun at charm:~$ cat foo.py
    colorIndex = 0
    
    def test():
        print colorIndex
    
    test()
    exarkun at charm:~$ python foo.py
    0
    exarkun at charm:~$                                           

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



More information about the Python-list mailing list