By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
439,941 Members | 1,789 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 439,941 IT Pros & Developers. It's quick & easy.

Scope question

P: n/a
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 ---

regards,
Subhash
--
Remove "nospam_" for direct reply
Jul 18 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
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()

Jul 18 '05 #2

P: n/a
Subhash Chandra <no**************@yahoo.com> writes:
How can I make counter variable in function foo reference to global
counter variable in the following code.
add the line " global counter" just after "def foo():"
Generally C programmers tend to write code like that I am looking
for simple way to do it in python.
Generally C programmers do horrible things. Please consider whether
you really, really should be emulating C style in Python.
--- BEGIN ---
counter = 0

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

foo()
--- END ---

Jul 18 '05 #3

P: n/a
Hello Subhash,
--- BEGIN ---
counter = 0

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

foo()
--- END ---

Today we have generators:
def foo(): for count in range(10):
print "count = ", count
yield count
count += 1 gen = foo()
gen.next() count = 0
0 gen.next() count = 1
1


HTH.
Miki
Jul 18 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.