Declare a variable global
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Feb 19 16:16:35 EST 2007
yinglcs at gmail.com a écrit :
> Hi,
>
> I have the following code:
>
> colorIndex = 0;
You don't need the ;
>
> def test():
> print colorIndex;
Idem.
> This won't work.
Why ?
Or more exactly : for which definition of "won't work" ? (hint: this
code prints 0 on sys.stdout - I don't know what else you where expecting...)
> But it works if i do this:
>
> colorIndex = 0;
>
> def test():
> global colorIndex;
> print colorIndex;
Have mercy : keep those ; out of here.
> My question is why do I have to explicit declaring 'global' for
> 'colorIndex'? Can't python automatically looks in the global scope
> when i access 'colorIndex' in my function 'test()'?
It does. You only need to declare a name global in a function if you
intend to rebind the name in the function.
More information about the Python-list
mailing list