Declare a variable global

Gary Herron gherron at digipen.edu
Mon Feb 19 12:58:51 EST 2007


yinglcs at gmail.com wrote:
> Hi,
>
> I have the following code:
>
> colorIndex = 0;
>
> def test():
>      print colorIndex;
>
> This won't work.   But it works if i do this:
>   
Yes, it does work. Can you be more explicit about why you think it doesn't?

(Also, this is Python not C/C++. Get *RID* of the semi-colons after your 
statements!)

> colorIndex = 0;
>
> def test():
>      global colorIndex;
>      print colorIndex;
>   
If you wish to change the value of colorIndex inside test, then this 
won't work

colorIndex = 0

def test():
     colorIndex=123   # creates a new variable within test

In the above case you'll end up with two variables of that name, one in the global context, and the other within test's context.

However, this code might be more what you want:

colorIndex = 0

def test():
     global colorIndex
     colorIndex=123   # changes the value of the global


Better yet, restructure your code to not rely on the global statement.  Do something like this if you can:


def test():
    return 123

colorIndex = test() 

Gary Herron

> 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()'?
>
> Thank you.
>
>   




More information about the Python-list mailing list