I thought I'd 'got' globals but...

Luis M. González luismgz at gmail.com
Fri Jul 7 19:01:20 EDT 2006


Bruno Desthuilliers wrote:
>
> def doIt(name=None):
>   global gname
>   if name is None:
>     name = gname
>   else:
>     gname = name
>

Sorry for this very basic question, but I don't understand why I should
add the global into the function body before using it.
This function works even if I don't add the global.
Just to try this out, I wrote this variant:

gname = 'Luis'

def doIt2(name=None):
	if name is None:
		name = gname
	return name

print doIt2()  --> returns Luis.

So, what's the point of writing the function this way instead?

def doIt2(name=None):
        global gname
	if name is None:
		name = gname
	return name


luis




More information about the Python-list mailing list