Newbie question
Paul Osman
paul.osman at sympatico.ca
Tue Apr 16 12:18:12 EDT 2002
Ante,
do some reading about scope... add the following line to dummy.py:
<code>
num = 0
def dummy():
global num
num += 1
dummy()
</code>
now in the interpretor:
>>> import dummy
>>> print dummy.num
1
>>> dummy.dummy()
>>> print dummy.num
2
HTH,
-Paul Osman
Ante wrote:
>from file 'dummy.py'
>----------------------------
>num = 0
>
>def dummy():
> num += 1
>
>dummy()
>----------------------------
>
>now, in the interpreter:
>
>>>>import dummy
>>>>
>Traceback (most recent call last):
> File "<string>", line 1, in ?
> File "C:\downloads\python2.2.1\dummy.py", line 6, in ?
> dummy()
> File "C:\downloads\python2.2.1\dummy.py", line 4, in dummy
> num += 1
>UnboundLocalError: local variable 'num' referenced before assignment
>
>
>Why does this happen?
>If I replace num += 1 with print num, it prints 0 without an error.
>I guess it scans the whole function and check if there's an assignment to a
>name,
>and if there is, assumes it's a local variable. But += isn't supposed to
>move the
>reference but instead change the same variable. Or what did I get wrong?
>
>Ante.
>
>
>
More information about the Python-list
mailing list