Global name "userid" not defined??

Peter Hansen peter at engcorp.com
Tue Mar 30 13:23:03 EST 2004


Sean Berry wrote:

> #!/usr/local/bin/python
> 
> def setUserid(value):
>     userid = value
> 
> def getUserid():
>     return userid
> 
> How do I make a variable global?

You need to use the "global" keyword (check the docs for more
information) with the name of the variable at the top of each
function which wants to *modify* the global variable (including by
creating it in the first place).

Although you don't need to include this ("global userid") in
the second function, it would probably be considered "good style".
Of course, using globals at all is pretty bad style, but as you're
just learning it's not the worst thing to do.  (Close, but not
the worst... just consider learning how to avoid them, generally
by making things more object-oriented.)

-Peter



More information about the Python-list mailing list