Newbie question

Paul Osman paul.osman at sympatico.ca
Tue Apr 16 13:40:48 EDT 2002


Ante wrote:

>Um.. and shouldn't one read the article before replying?
>
>If this is solely a scope problem, then why does it work if you replace
>'num += 1' with 'print num'?
>
>Shouldn't it say 'referencing local before assignment yada yada yada'
>anyway?
>
>My question was: why does it work if you only use the variable, and doesn't
>work if you assign to it? I guess it would actually make sense for plain
>assignment, but for += operator, it doesn't seem so.
>
Okay, let me try this again... Python detects local names statically. 
Variables assigned in a function are classified as local by default. 
therefore in the following script:

<code>
num = 1

def dummy():
    num = 5
    return num

print dummy()
print num
</code>

The output will be:
5
1
This is because there are actually two variables named "num", one 
global, and one local to the function dummy(). Now, if we were to do 
take out the assignment from the dummy() function, the output would be:
1
1
Hence in this case, 'num' represents only one variable (with global 
scope). This is why your print statement worked inside the function. The 
print was referring to the 'num' with global scope.

Now, as for why an assignment won't work, well, if you did this:
<code>
num = 5
def dummy():  
    num = 1
    return num
</code>
You would be creating one variable with global scope called num and one 
with function level scope called num. Note that the function level 
variable is destroyed once the function is finished. Therefore the += 
operation you were attempting before wouldn't make much sense... if the 
variable only exists within the function? global variables are immutable 
from within functions. Consider this:
<code>
num = 5
def dummy():
    newnum = num + 5
    return num
</code>
the function dummy() will now return 6. Because you were not changing 
the value of 'num'.

Any of this clear? Forgive me, I'm not the best at explaining things, 
but hopefully this should shed some light..

-Paul







More information about the Python-list mailing list