learning-python question
David Goodger
dgoodger at bigfoot.com
Sat Jul 29 00:18:22 EDT 2000
on 2000-07-28 23:02, gbp (gpepice1 at nycap.rr.com) wrote:
> I'm new to python but it looks like your varible is out of scope. Try
> declaring it as a global (just put the work global in front of it) or
> try moving it so its inside the function. It you declare a varible at
> top level its isn't automatically global. Its local to the top level.
>
> JeremyLynch at fsmail.net wrote:
>> count = 5
>>
>> def count_func()
>> print count
>> count = count + 1
>>
>> count_func()
>>
>> Why can count_func() not see count (it throws up a 'name'
>> or 'attribute' error)
Almost. The variable "count" is global, which means it's visible inside
count_func(). But when you say "count = count + 1", you're first referring
to the global variable count, adding 1 to its value, then assigning that
value to a new local variable count. This is not allowed in Python; you
cannot refer to an unqualified name both globally and locally in the same
function.
The solution is to put "global count" inside the function, *before* you
first refer to the variable (the first line is a good place).
Why not make count_func into a real function? (I assume that your real
intention is more complex than the example above.) Viz:
def count_func(count):
print count
return count + 1
count = 5
count = count_func(count)
--
David Goodger dgoodger at bigfoot.com Open-source projects:
- The Go Tools Project: http://gotools.sourceforge.net
(more to come!)
More information about the Python-list
mailing list