I thought I'd 'got' globals but...
nate
n8pease at yahoo.com
Fri Jul 7 19:34:24 EDT 2006
try this:
gname = 'nate'
def test():
gname = 'amy'
print gname
test()
print gname
outputs:
'amy'
'nate'
whereas this:
gname = 'nate'
def test():
global gname
gname = 'amy'
print gname
test()
print gname
outputs:
'amy'
'amy'
Luis M. González wrote:
> 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