Behaviour of print in functions

Christophe Delord christophe.delord at free.fr
Wed Jul 10 16:40:14 EDT 2002


You must use the global statement to assign global variables :

http://www.python.org/doc/current/ref/global.html

-----
The global statement is a declaration which holds for the entire current code block. It means that the listed identifiers are to be interpreted as globals. While using global names is automatic if they are not defined in the local scope, assigning to global names would be impossible without global.
-----

Try this :

def foo():
	global X
	print X
	X = 100
	print X



Christophe.


On Wed, 10 Jul 2002 20:11:33 GMT
"Craig McLean" <craigmclean at shaw.ca> wrote:

> I'm learning Python and I have run into something I can't explain.  I have
> the following code
> 
> X = 99
> def foo():
>     print X
>     X = 100
>     print X
> 
> foo()
> 
> When I call foo it complains that local variable X is referenced before been
> assigned.  However X is a global and I was under the impression that it
> should realize that and resolve it automatically.
> 
> I know that if you add a "global X" as the first line of function foo then
> this all works properly.
> 
> I also know that
> 
> X=99
> def qux():
>     print X
> 
> qux()
> 
> prints 99 as I would expect.
> 
> I'm assuming what is happening is that name resolutions use the LGB rule,
> but assignments always create a new entry in the local namespace, without
> checking to see if it is covering up a global object of the same name.  I'm
> also assuming that this happens before any of the code in the function is
> executed.
> 
> Am I correct?  Or is something else happening here.
> 
> 
> 


-- 

(o_   Christophe Delord                   _o)
//\   http://christophe.delord.free.fr/   /\\
V_/_  mailto:christophe.delord at free.fr   _\_V



More information about the Python-list mailing list