61
3.10. Glossary
39
Syntaxerrorsareusuallyeasytofind,butthereareafewgotchas.Whitespaceer-
rorscanbetrickybecausespacesandtabsareinvisibleandweareusedtoignoring
them.
>>> x x = = 5
>>>
y = = 6
File "<stdin>", , line 1
y = = 6
ˆ
SyntaxError: invalid syntax
Inthisexample,theproblemisthatthesecondlineisindentedbyonespace.But
theerrormessagepointsto
y
, whichismisleading. . Ingeneral,errormessages
indicatewheretheproblemwasdiscovered,buttheactualerrormightbeearlier
inthecode,sometimesonapreviousline.
Thesameistrueofruntimeerrors.Supposeyouaretryingtocomputeasignal-to-
noiseratioindecibels.TheformulaisSNR
db
=10log
10
(P
signal
/P
noise
). InPython,
youmight write something like this:
import math
signal_power = 9
noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels
But when you run it, you getan error message
1
:
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
OverflowError: math range error
The 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 signalpower and noise power with floating-
point values.
In general, error messages tell you where the problem was discovered, but that is
often not where it was caused.
3.10 Glossary
body: The sequence of statements within a compound statement.
boolean expression: An expressionwhose value is either
True
or
False
.
1
InPython3.0,younolongergetanerrormessage;thedivisionoperatorperformsfloating-point
divisionevenwithintegeroperands.