[EMAIL PROTECTED] said unto the world upon
2005-05-07 09:56:
> Good morning,
>
> I came across a rather odd issue with scoping. Can someone explain why
> testa and testc works, but not testb. I am running under python 2.4.1 on
> Windows NT.
>
> thanks,
> Michael
<SNIP>
> def testb(astr):
> x = x - 1
> print astr, x
`x =', with a function def, gets interpreted as "create a new name x
in the function-local scope and bind it to whatever is on the right of
the `='. But, on the right is an _expression_ involving x itself. You
might expect Python to look to the global scope to find x, but by
writing `x =', you've already settled that x will be a local scope
name, so it looks only in the local scope. Of, course, when it gets to
`x -1', x hasn't yet been given a reference and it all barfs.
This is what the global statement is for:
def testb(astr):
global x
x = x - 1
etc.
mailto:[EMAIL PROTECTED]
510 558 3275 home
720 938 2625 cell
_______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor