On May 4, 12:39 pm, 7stud <[EMAIL PROTECTED]> wrote:
> On May 4, 3:30 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Hi,
>
> > Can anyone explain the following:
>
> > Python 2.5 (r25:51908, Apr  9 2007, 11:27:23)
> > [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > def foo():
>
> > ...     x = 2
> > ...>>> foo()
> > >>> def bar():
>
> > ...     x[2] = 2
> > ...
>
> > >>> bar()
>
> > Traceback (most recent call last):
> >   File "<stdin>", line 1, in <module>
> >   File "<stdin>", line 2, in bar
> > NameError: global name 'x' is not defined
>
> > Thanks,
> > Jianbing
>
> The first function is completely irrelevant unless you expect this to
> work:
>
> x = 2
> x[2] = 2
>
> Traceback (most recent call last):
>   File "test1.py", line 2, in ?
>     x[2] = 2
> TypeError: object does not support item assignment
>
> So that leaves you with:
>
> > >>> def bar():
>
> > ...     x[2] = 2
> > ...
>
> > >>> bar()
>
> Would you expect this to work:
>
> x[2] = 2
> print x

I will sympathize with the OP to the extent that the message "global
name 'x' is not defined" is a bit misleading. All that the interpreter
really knows is that 'x' is not defined, locally or globally, and it
should probably not presume to guess the coder's intention.


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to