Global confusion
William Park
parkw at better.net
Tue Sep 28 18:22:08 EDT 1999
On Tue, Sep 28, 1999 at 09:25:28PM +0000, Gaetan Corneau wrote:
> Hello,
>
> I often use scripts like this:
>
> n = "Hello!"
>
> def F():
> print n
>
> F()
>
>
> Today, a friend of mine (a newbie) who is trying to use Python with word,
> wrote the following:
>
> import win32com.client.dynamic
>
> Srv = win32com.client.dynamic.Dispatch("word.application")
>
> Srv.Documents("Document1").Activate # Word must already be running and have
> document1 open
>
> nbPar = Srv.ActiveDocument.Paragraphs.Count
> Srv.ActiveDocument.Paragraphs(nbPar).Range.InsertParagraphAfter()
>
>
> # Function to add a paragraph
> def AddParagraph(style, text):
> Srv.ActiveDocument.Paragraphs[nbPar].Range.InsertParagraphAfter()
> Srv.ActiveDocument.Paragraphs[nbPar].Range.Style =
> Srv.ActiveDocument.Styles(style)
> Srv.ActiveDocument.Paragraphs[nbPar].Range.InsertAfter(text)
> nbPar = nbPar + 1
>
> # Create a section
> def AddObjectSection(objName):
> AddParagraph("Heading 1", objName)
>
>
> AddObjectSection("Customer")
>
> and he got the following:
>
> Traceback (innermost last):
> File "D:\harddisk\temp\dantest.py", line 24, in ?
> AddObjectSection("Customer")
> File "D:\harddisk\temp\dantest.py", line 21, in AddObjectSection
> AddParagraph("Heading 1", objName)
> File "D:\harddisk\temp\dantest.py", line 14, in AddParagraph
> Srv.ActiveDocument.Paragraphs[nbPar].Range.InsertParagraphAfter()
> NameError: nbPar
>
> I looked in my "Learning Python" book and told my friend to insert "global
> nbPar" as the first line of the "AddParagraph" function.
> It works, but I don't understand why he has to do that...
>
> Anybody who can exlain?
Probably, the line
nbPar = nbPar + 1
is telling the python interpretor that 'nbPar' is a local variable,
since it is being assigned. So, when local namespace is searched,
it's not there.
I encountered this kind of problem often, where a variable occurs on
both side of '=' for the first time.
Yours truly,
William Park
More information about the Python-list
mailing list