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.

46 Chapter 5. Conditionals and recursion• What kind of erroritwas, and• Where itoccurred.Syntax errors are usually easy to find, but there are a few gotchas. Whitespace errors can be trickybecause spaces and tabs are invisibleand weareused toignoring them.>>> x = 5>>> y = 6File "", line 1y = 6ˆSyntaxError: invalid syntaxIn this example, the problem is that the second line is indented by one space. But the error messagepoints to y, which is misleading. In general, error messages indicate where the problem wasdiscovered, but theactual error might be earlier inthecode, sometimes on aprevious line.The same is true of runtime errors. Suppose you are trying to compute a signal-to-noise ratio indecibels. The formula is SNR db = 10log 10 (P signal /P noise ). In <strong>Python</strong>, you might write somethinglikethis:import mathsignal_power = 9noise_power = 10ratio = signal_power / noise_powerdecibels = 10 * math.log10(ratio)print decibelsBut when you runit,you get anerror message 2 :Traceback (most recent call last):File "snr.py", line 5, in ?decibels = 10 * math.log10(ratio)OverflowError: math range errorThe error message indicates line 5, but there is nothing wrong with that line. To find the real error,it might be useful to print the value of ratio, which turns out to be 0. The problem is in line 4,because dividing two integers does floor division. The solution is to represent signal power andnoise power withfloating-point values.In general, error messages tell you where the problem was discovered, but that is often not where itwas caused.5.13 Glossarymodulus operator: Anoperator,denotedwithapercentsign(%),thatworksonintegersandyieldsthe remainder when one number isdivided by another.boolean expression: Anexpression whose value is eitherTrueorFalse.2 In <strong>Python</strong> 3.0, you no longer get an error message; the division operator performs floating-point division even withintegeroperands.

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

Saved successfully!

Ooh no, something went wrong!