[Tutor] Question on a example in the book "Learn to program using python" by Alan Gauld

Kent Johnson kent_johnson at skillsoft.com
Sun Aug 1 17:27:33 CEST 2004


Klas,

The try / except block in your main program is hiding a lot of useful 
information from you - the details of what type of exception was thrown, 
and where the problem occurs. If a Python program exits by throwing an 
exception, the Python runtime prints this information. By catching the 
exception you are losing this information.

Taking out the try / except, the main program looks like this:
if __name__ == "__main__":
     if len (sys.argv) <> 2:
         print "Usage: python document.py"
         sys.exit()
     else:
         D = HTMLDocument(sys.argv[1])
         D.Analyze()
         D.printStats()

If I run the program now, it outputs
Traceback (most recent call last):
   File "document.py", line 130, in ?
     D.Analyze()
   File "document.py", line 70, in Analyze
     self.generateStats()
   File "document.py", line 54, in generateStats
     sentence_count = sentence_count + \
UnboundLocalError: local variable 'sentence_count' referenced before assignment

This is much more useful. Apparently the variable sentence_count is being 
used before it is initialized. The problem is at line 54, which reads
             sentence_count = sentence_count + \
                              self.punctuation_counts[c]

sentence_count is an instance variable and you have forgotten the self 
qualifier. These lines should read
             self.sentence_count = self.sentence_count + \
                              self.punctuation_counts[c]

Fixing this gets past the original error. There are several similar errors 
that I will let you find :-)

Kent

At 05:10 PM 8/1/2004 +0200, Klas Marteleur wrote:
>Hi
>
>First of all thanks for a interesting mailing list, i think i learn a lot by
>reading all good questions and answers.
>
>I bought a copy of the great book "Learn o program using python" 2001, i have
>read it back and forth a couple of times and now i am going thru testing and
>trying to understand all examples (...i think i am slowly starting to learn
>:) )
>
>I got stuck on the case studie for the very useful :) program "Grammar
>counter" though.
>No matter what i try i get the error "Error analyzing file....."
>
>I type "python document.py example_file.txt" in a console.
>
>Can somebody of you professionals point me to what i am doing wrong?
>
>Many thanks
>Klas Marteleur



More information about the Tutor mailing list