Newbie question

Erik Max Francis max at alcyone.com
Tue Apr 16 14:37:28 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'?

Because Python looks for variables differently if a name is being bound
(or rebound) instead of simply referenced.

If you simply reference the name (e.g., print num), the interpreter has
no problem figuring out you mean the global num.  If you bind it (num =
...) however, the interpreter can't know whether you mean the global num
or a new, local num.  So you have to tell the interpeter you mean the
global one with the use of the global keyword (global num).

My advice to people new to these scopes issues is to always use the
global keyword when you're referencing global variables, even when it's
not strictly required.  This helps make code more self-documenting,
makes it clear to others (including yourself at a later time) what you
had intended to do, and means you don't have to modify your code later
should you decide to change a simple reference into a binding later on.

> Shouldn't it say 'referencing local before assignment yada yada yada'
> anyway?

No, because num += 1 is determines to refer to a local variable, and (in
this case) expands to num = num + 1; it's the second num -- the
reference -- that it's complaining about, since it's already determined
that you mean the local binding, not the global one.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ Nationalism is an infantile sickness.
\__/ Albert Einstein
    Alcyone Systems' Daily Planet / http://www.alcyone.com/planet.html
 A new, virtual planet, every day.



More information about the Python-list mailing list