Declare a variable global

Bjoern Schliessmann usenet-mail-0306.20.chr0n0ss at spamgourmet.com
Mon Feb 19 13:04:20 EST 2007


yinglcs at gmail.com wrote:

> I have the following code:
> 
> colorIndex = 0;
> 
> def test():
>      print colorIndex;

Don't use ";". It's redundant.
 
> This won't work.   But it works if i do this:
> 
> colorIndex = 0;
> 
> def test():
>      global colorIndex;
>      print colorIndex;
> 
> My question is why do I have to explicit declaring 'global' for
> 'colorIndex'?

Because you could want to have an identifier called colorIndex in
test's scope. Globals are infrequently used in Python, thus the
more common case is assumed by default.

> Can't python automatically looks in the global scope when i
> access 'colorIndex' in my function 'test()'? 

No, it can't looks.

Regards,


Björn

-- 
BOFH excuse #66:

bit bucket overflow




More information about the Python-list mailing list