newbie questions
Mike Meyer
mwm at mired.org
Sat Dec 11 01:32:14 EST 2004
Adam DePrince <adam at cognitcorp.com> writes:
> Alright. Now, as Erik pointed out if you assign to the variable the
> computer will add that to the local name space. This happens at
> "compile" time (which is right after you hit enter twice at the CPython
> command line.)
>
> For an example of this:
>
>>>> a = 0
>>>> def b():
> ... print a
> ...
>>>> def c():
> ... print a
> ... a = 1
> ...
>>>> b()
> 0
>>>> c()
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> File "<stdin>", line 2, in c
> UnboundLocalError: local variable 'a' referenced before assignment
>
> In b(), a was taken as being from the line above. In c, it was from the
> local name space.
>
> So, how do we affect what you want?
I *have* to point out here that you can write c as:
>>> a = 2
>>> def c():
... global a
... print a
... a = 1
...
>>> c()
2
>>>
The one (and so far only) place you can declare a variable in Python.
<mike
--
Mike Meyer <mwm at mired.org> http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
More information about the Python-list
mailing list