learning-python question
Trent Mick
trentm at activestate.com
Mon Jun 26 20:07:53 EDT 2000
On Mon, Jun 26, 2000 at 08:34:43PM +0000, JeremyLynch at fsmail.net wrote:
> hi,
> I have just started learning python, although I am already confident in
> c/c++, and I finding some of python's features confusing. This may seem
> like a *very* stupid question so ignore it if you want to :)
> My problem simplifies to:
>
> count = 5
>
> def count_func()
> print count
^^^^^
This reference to count is raising a NameError. This is because the global
namespace is not searched when in a Python function. You have to explicitly
declare any global variables used in a function with the 'global' keyword,
> count = count + 1
so.... this is what you want:
c:\temp> python
>>> count = 5
>>>
>>> def count_func():
... global count
... print count
... count = count + 1
...
>>>
>>> count_func()
5
>>> count_func()
6
>>>
As well, you have to have a colon after the 'def count_func()'.
Trent
--
Trent Mick
trentm at activestate.com
More information about the Python-list
mailing list