12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

A.3. Semantic errors 201The explicit version is easier to read because the variable names provide additional documentation,and it is easier to debug because you can check the types of the intermediate variables and displaytheir values.Anotherproblemthatcanoccurwithbigexpressionsisthattheorderofevaluationmaynotbewhatyou expect. For example, ifyou aretranslatingthe expression2π x into<strong>Python</strong>, you might write:y = x / 2 * math.piThat is not correct because multiplication and division have the same precedence and are evaluatedfrom lefttoright. Sothis expression computes xπ/2.A good waytodebug expressions istoadd parentheses tomake theorder ofevaluation explicit:y = x / (2 * math.pi)Whenever you are not sure of the order of evaluation, use parentheses. Not only will the programbe correct (in the sense of doing what you intended), it will also be more readable for other peoplewho haven’t memorized therules of precedence.A.3.3 I’ve got afunction or methodthatdoesn’treturnwhatIexpect.If you have a return statement with a complex expression, you don’t have a chance to print thereturnvalue before returning. Again, you can use atemporary variable. For example, insteadof:return self.hands[i].removeMatches()you could write:count = self.hands[i].removeMatches()return countNow you have the opportunity todisplay thevalue ofcountbeforereturning.A.3.4 I’m really,really stuckandIneedhelp.First, try getting away from the computer for a few minutes. Computers emit waves that affect thebrain, causing thesesymptoms:• Frustration and rage.• Superstitious beliefs (“the computer hates me”) and magical thinking (“the program onlyworks when Iwear myhat backward”).• Random walk programming (the attempt to program by writing every possible program andchoosing the one that does theright thing).If you find yourself suffering from any of these symptoms, get up and go for a walk. When you arecalm, think about the program. What is it doing? What are some possible causes of that behavior?When was the lasttimeyou had aworking program, and what did you donext?Sometimesitjusttakestimetofindabug. IoftenfindbugswhenIamawayfromthecomputerandletmymindwander. Someofthebestplacestofindbugsaretrains,showers,andinbed,justbeforeyou fallasleep.

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

Saved successfully!

Ooh no, something went wrong!