12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Appendix ADebuggingDifferentkindsoferrorscanoccurinaprogram,anditisusefultodistinguishamongtheminordertotrackthem down morequickly:• Syntax errors are produced by <strong>Python</strong> when it is translating the source code into byte code.Theyusuallyindicatethatthereissomethingwrongwiththesyntaxoftheprogram. Example:Omitting the colon at the end of a def statement yields the somewhat redundant messageSyntaxError: invalid syntax.• Runtimeerrorsareproduced bytheinterpreterifsomethinggoeswrongwhiletheprogram isrunning. Mostruntimeerrormessagesincludeinformationaboutwheretheerroroccurredandwhatfunctionswereexecuting. Example: Aninfiniterecursioneventually causestheruntimeerror “maximum recursion depth exceeded.”• Semantic errors are problems with a program that runs without producing error messages butdoesn’t do the right thing. Example: An expression may not be evaluated in the order youexpect, yielding anincorrect result.The first step in debugging is to figure out which kind of error you are dealing with. Although thefollowing sections are organized by error type, some techniques are applicable in more than onesituation.A.1 Syntax errorsSyntax errors are usually easy to fix once you figure out what they are. Unfortunately, the errormessagesareoftennothelpful. ThemostcommonmessagesareSyntaxError: invalid syntaxandSyntaxError: invalid token,neither of which isvery informative.On the other hand, the message does tell you where in the program the problem occurred. Actually,ittellsyouwhere<strong>Python</strong>noticedaproblem,whichisnotnecessarilywheretheerroris. Sometimestheerror isprior tothelocation of the errormessage, oftenon the preceding line.If you are building the program incrementally, you should have a good idea about where the erroris. Itwillbe inthelast lineyou added.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!