Scope question

Gandalf gandalf at geochemsource.com
Thu Mar 11 02:56:12 EST 2004


Subhash Chandra wrote:

> Hi,
>
> How can I make counter variable in function foo reference to global 
> counter variable in the following code. Generally C programmers tend 
> to write code like that I am looking for simple way to do it in python.
>
> --- BEGIN ---
> counter = 0
>
> def foo():
> if counter < 10:
> print "count = ", counter
> counter += 1
>
> foo()
> --- END ---

You need to tell explicitly that the name 'counter' is global. It is 
because used this statment in your function:

counter += 1

which is a rebind of the name 'counter'. So python thinks it must be a 
local name.
Here is what you want:

counter = 0

def foo():
global counter
if counter < 10:
print "count = ", counter
counter += 1

foo()






More information about the Python-list mailing list