49
2.12. Choosingmnemonicvariablenames
27
ThePythoninterpreterseesallthreeoftheseprogramsasexactlythesamebut
humansseeandunderstandtheseprogramsquitedifferently. Humanswillmost
quicklyunderstandtheintentofthesecondprogrambecausetheprogrammerhas
chosenvariablenamesthatreflecttheintentoftheprogrammerregardingwhat
datawillbestoredineachvariable.
Wecallthesewisely-chosenvariablenames“mnemonicvariablenames”. The
wordmnemonic
4
means“memoryaid”. Wechoosemnemonicvariablenamesto
helpusrememberwhywecreatedthevariableinthefirstplace.
Whilethisallsoundsgreat,anditisaverygoodideatousemnemonicvariable
names,mnemonicvariablenamescangetinthewayofabeginningprogrammer’s
abilitytoparseandunderstandcode.Thisisbecausebeginningprogrammershave
notyetmemorizedthereservedwords(thereareonly31ofthem)andsometimes
variableswhichhavenamesthataretoodescriptivestarttolooklikepartofthe
languageandnotjustwell-chosenvariablenames.
TakeaquicklookatthefollowingPythonsamplecodewhichloopsthroughsome
data. Wewillcoverloopssoon,butfornowtrytojustpuzzlethroughwhatthis
means:
for word in words:
print word
Whatishappeninghere? Whichofthetokens(for,word,in,etc.) ) arereserved
wordsandwhicharejustvariablenames? DoesPythonunderstandatafunda-
mentallevelthenotionofwords?Beginningprogrammershavetroubleseparating
whatpartsofthecodemustbethesameasthisexampleandwhatpartsofthecode
aresimplychoicesmadebytheprogrammer.
Thefollowingcodeisequivalenttotheabovecode:
for slice in pizza:
print slice
Itiseasierforthebeginningprogrammertolookatthiscodeandknowwhich
partsarereservedwordsdefinedbyPythonandwhichpartsaresimplyvariable
nameschosenbytheprogrammer.ItisprettyclearthatPythonhasnofundamental
understandingofpizzaandslicesandthefactthatapizzaconsistsofasetofone
ormoreslices.
Butifourprogramistrulyaboutreadingdataandlookingforwordsinthedata,
pizza
and
slice
areveryun-mnemonicvariablenames.Choosingthemasvari-
ablenamesdistractsfromthemeaningoftheprogram.
Afteraprettyshortperiodoftime,youwillknow themostcommonreserved
wordsandyouwillstarttoseethereservedwordsjumpingoutatyou:
4
See
http://en.wikipedia.org/wiki/Mnemonic
foranextendeddescriptionoftheword
“mnemonic”.
78
28
Chapter2. Variables,expressionsandstatements
for
word
in
words
:
print
word
ThepartsofthecodethataredefinedbyPython(
for
,
in
,
print
,and
:
)areinbold
andtheprogrammerchosenvariables(
word
and
words
)arenotinbold.Manytext
editorsareawareofPythonsyntaxandwillcolorreservedwordsdifferentlytogive
youcluestokeepyourvariablesandreservedwordsseparate. Afterawhileyou
willbegintoreadPythonandquicklydeterminewhatisavariableandwhatisa
reservedword.
2.13 Debugging
Atthispointthesyntaxerroryouaremostlikelytomakeisanillegalvariable
name,like
class
and
yield
,whicharekeywords,or
odd˜job
and
US$
,which
containillegalcharacters.
Ifyouputaspaceinavariablename,Pythonthinksitistwooperandswithoutan
operator:
>>> bad name = 5
SyntaxError: invalid syntax
For syntax errors, the error messages don’t help much. . The e most common
messagesare
SyntaxError:
invalid syntax
and
SyntaxError:
invalid
token
,neitherofwhichisveryinformative.
Theruntimeerroryouaremostlikelytomakeisa“usebeforedef;”thatis,trying
touseavariablebeforeyouhaveassignedavalue.Thiscanhappenifyouspella
variablenamewrong:
>>> principal = = 327.68
>>> interest = principle * * rate
NameError: name
'
principle
'
is not t defined
Variablesnamesarecasesensitive,so
LaTeX
isnotthesameas
latex
.
Atthispointthemostlikelycauseofasemanticerroristheorderofoperations.
Forexample,toevaluate
1
2π
,youmightbetemptedtowrite
>>> 1.0 / 2.0 * * pi
Butthedivisionhappensfirst,soyouwouldgetπ/2,whichisnotthesamething!
ThereisnowayforPythontoknowwhatyoumeanttowrite,sointhiscaseyou
don’tgetanerrormessage;youjustgetthewronganswer.
2.14 Glossary
assignment: Astatementthatassignsavaluetoavariable.
47
2.14. Glossary
29
concatenate: Tojointwooperandsend-to-end.
comment: Informationinaprogramthatismeantforotherprogrammers(orany-
onereadingthesourcecode)andhasnoeffectontheexecutionofthepro-
gram.
evaluate: Tosimplifyanexpressionbyperformingtheoperationsinordertoyield
asinglevalue.
expression: Acombinationofvariables,operators,andvaluesthatrepresentsa
singleresultvalue.
floating-point: Atypethatrepresentsnumberswithfractionalparts.
floordivision: Theoperationthatdividestwonumbersandchopsoffthefraction
part.
integer: Atypethatrepresentswholenumbers.
keyword: Areservedwordthatisusedbythecompilertoparseaprogram;you
cannotusekeywordslike
if
,
def
,and
while
asvariablenames.
mnemonic: Amemoryaid.Weoftengivevariablesmnemonicnamestohelpus
rememberwhatisstoredinthevariable.
modulusoperator: Anoperator,denotedwithapercentsign(
%
),thatworkson
integersandyieldstheremainderwhenonenumberisdividedbyanother.
operand: Oneofthevaluesonwhichanoperatoroperates.
operator: Aspecialsymbolthatrepresentsasimplecomputationlikeaddition,
multiplication,orstringconcatenation.
rulesofprecedence: Thesetofrulesgoverningtheorderinwhichexpressions
involvingmultipleoperatorsandoperandsareevaluated.
statement: Asectionofcodethatrepresentsacommandoraction. . Sofar,the
statementswehaveseenareassignmentsandprintstatements.
string: Atypethatrepresentssequencesofcharacters.
type: Acategoryofvalues.Thetypeswehaveseensofarareintegers(type
int
),
floating-pointnumbers(type
float
),andstrings(type
str
).
value: Oneofthebasicunitsofdata,likeanumberorstring, , thataprogram
manipulates.
variable: Anamethatreferstoavalue.
35
30
Chapter2. Variables,expressionsandstatements
2.15 Exercises
Exercise2.2 Writeaprogramthatuses
raw_input
topromptauserfortheir
nameandthenwelcomesthem.
Enter your name: Chuck
Hello Chuck
Exercise2.3 Writeaprogramtoprompttheuserforhoursandrateperhourto
computegrosspay.
Enter Hours: : 35
Enter Rate: 2.75
Pay: 96.25
Wewon’tworryaboutmakingsureourpayhasexactlytwodigitsafterthedecimal
placefornow.Ifyouwant,youcanplaywiththebuilt-inPython
round
function
toproperlyroundtheresultingpaytotwodecimalplaces.
Exercise2.4 Assumethatweexecutethefollowingassignmentstatements:
width = = 17
height = 12.0
Foreachofthefollowingexpressions,writethevalueoftheexpressionandthe
type(ofthevalueoftheexpression).
1.
width/2
2.
width/2.0
3.
height/3
4.
1 + 2 * 5
UsethePythoninterpretertocheckyouranswers.
Exercise2.5 WriteaprogramwhichpromptstheuserforaCelsiustemperature,
convertthetemperaturetoFahrenheitandprintouttheconvertedtemperature.
67
Chapter3
Conditionalexecution
3.1 Booleanexpressions
Abooleanexpressionisanexpressionthatiseithertrueorfalse.Thefollowing
examplesusetheoperator
==
,whichcomparestwooperandsandproduces
True
iftheyareequaland
False
otherwise:
>>> 5 5 == = 5
True
>>> 5 5 == = 6
False
True
and
False
arespecialvaluesthatbelongtothetype
bool
; theyare not
strings:
>>> type(True)
<type
'
bool
'
>
>>> type(False)
<type
'
bool
'
>
The
==
operatorisoneofthecomparisonoperators;theothersare:
x != y
# x is not t equal l to o y
x > y
# x is greater than n y
x < y
# x is less than y
x >= y
# x is greater than n or r equal to y
x <= y
# x is less than or r equal l to y
x is y
# x is the e same e as y
x is not y
# x is not t the e same e as s y
Althoughtheseoperationsareprobablyfamiliartoyou,thePythonsymbolsare
differentfromthemathematicalsymbols.Acommonerroristouseasingleequal
sign(
=
)insteadofadoubleequalsign(
==
). Rememberthat
=
isanassignment
operatorand
==
isacomparisonoperator.Thereisnosuchthingas
=<
or
=>
.
VB.NET Image: Image and Doc Windows, Web & Mobile Viewers of to load, view, annotate, edit and save document image like Firefox, Internet Explorer, Google Chrome, Safari, etc. are JPEG, PNG, BMP, GIF, TIFF, PDF, Word and
add text field to pdf; pdf form change font size
58
32
Chapter3. Conditionalexecution
3.2 Logicaloperators
Therearethreelogicaloperators:
and
,
or
,and
not
.Thesemantics(meaning)of
theseoperatorsissimilartotheirmeaninginEnglish.Forexample,
x > 0 and x < 10
istrueonlyif
x
isgreaterthan0andlessthan10.
n%2 == 0 or n%3 == 0
istrueifeitheroftheconditionsistrue,thatis,ifthe
numberisdivisibleby2or3.
Finally,the
not
operatornegatesabooleanexpression,so
not (x > y)
istrueif
x > y
isfalse,thatis,if
x
islessthanorequalto
y
.
Strictlyspeaking,theoperandsofthelogicaloperatorsshouldbebooleanexpres-
sions,butPythonisnotverystrict.Anynonzeronumberisinterpretedas“true.”
>>> 17 7 and d True
True
Thisflexibilitycanbeuseful, butthere aresomesubtletiestoitthatmightbe
confusing.Youmightwanttoavoidit(unlessyouknowwhatyouaredoing).
3.3 Conditionalexecution
Inordertowriteusefulprograms,wealmostalwaysneedtheabilitytocheckcon-
ditionsandchangethebehavioroftheprogramaccordingly. Conditionalstate-
mentsgiveusthisability.Thesimplestformisthe
if
statement:
if x > > 0 0 :
print
'
x is s positive
'
Thebooleanexpressionafterthe
if
statementiscalledthecondition.Weendthe
if
statementwithacoloncharacter(:) andtheline(s)aftertheifstatementare
indented.
x > 0
print 'x is positive'
yes
no
If the logical condition is true, then the indented statement gets executed. If the
logicalcondition isfalse, theindented statementis skipped.
VB.NET Image: Web Image and Document Viewer Creation & Design with most modern browsers, including IE7+, Chrome, Firefox and images as JPEG, BMP, GIF, PNG, TIFF, PDF, etc. Upload, Open, Save & Download Images & Docs with
pdf add signature field; create a pdf form in word C# TIFF: C#.NET Code to Create Online TIFF Document Viewer with particular text or graphics; Save TIFF image Support modern browsers, including IE, Chrome, Firefox, Safari, etc to create more web viewers on PDF and Word
changing font size in a pdf form; changing font size in pdf form field
59
3.4. Alternativeexecution
33
if
statements have the same structure as function definitions or
for
loops. The
statement consistsofa headerlinethatends with thecolon character(:) followed
by an indented block. Statements like this are called compound statements be-
causethey stretch acrossmorethan oneline.
Thereisnolimiton thenumberofstatementsthatcan appearinthebody,butthere
hasto be at least one. Occasionally,it isusefulto haveabody with no statements
(usually as aplacekeeper for codeyou haven’t written yet). In that case,you can
usethe
pass
statement, which doesnothing.
if x < 0 :
pass
# need to handle negative values!
Ifyou enteranif statementin thePython interpreter,thepromptwillchangefrom
threechevrons to threedots to indicate you are in themiddle of a block of state-
mentsasshown below:
>>> x = 3
>>> if x < 10:
...
print
'
Small
'
...
Small
>>>
3.4 Alternative execution
Asecond formofthe
if
statementisalternativeexecution,in whichtherearetwo
possibilities and the condition determines which one gets executed. The syntax
lookslikethis:
if x%2 == 0 :
print
'
x is even
'
else :
print
'
x is odd
'
Iftheremainder when
x
is divided by 2 is0,then we knowthat
x
iseven, and the
program displays amessageto that effect. If thecondition isfalse,thesecond set
of statementsisexecuted.
x%2 == 0
print 'x is even'
yes
no
print 'x is odd'
68
34
Chapter3. Conditionalexecution
Since the condition must be true or false, exactly one of the alternatives will be
executed. The alternatives arecalled branches, because they are branches in the
flowof execution.
3.5 Chained conditionals
Sometimes there are more than two possibilities and we need more than two
branches. Onewayto expressa computation likethat isachained conditional:
if x < y:
print
'
x is less than y
'
elif x > y:
print
'
x is greater than y
'
else:
print
'
x and y are equal
'
elif
is an abbreviation of “elseif.” Again, exactly onebranch willbe executed.
x < y
print 'less'
yes
yes
x > y
print 'equal'
print 'greater'
There is no limit on the number of
elif
statements. If thereis an
else
clause, it
hasto beattheend,but theredoesn’t haveto beone.
if choice ==
'
a
'
:
print
'
Bad guess
'
elif choice ==
'
b
'
:
print
'
Good guess
'
elif choice ==
'
c
'
:
print
'
Close, but not correct
'
Each condition is checked in order. If thefirstis false,thenextis checked, and so
on. If oneof them is true, the corresponding branch executes, and thestatement
ends. Even if morethan onecondition istrue,only thefirsttruebranch executes.
58
3.6. Nested conditionals
35
3.6 Nested conditionals
One conditional can also be nested within another. We could have written the
trichotomyexamplelikethis:
if x == y:
print
'
x and y are equal
'
else:
if x < y:
print
'
x is less than y
'
else:
print
'
x is greater than y
'
The outer conditional contains two branches. The first branch contains a sim-
ple statement. The second branch contains another
if
statement, which has two
branches of its own. Those two branches are both simple statements, although
theycouldhavebeen conditionalstatementsaswell.
x == y
print 'greater'
yes
print 'less'
x < y
print 'equal'
no
no
yes
Although the indentation of the statements makes the structure apparent, nested
conditionalsbecomedifficult to read very quickly. In general,it isagood ideato
avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements.
For example,we can rewritethefollowing codeusing asingleconditional:
if 0 < x:
if x < 10:
print
'
x is a positive single-digit number.
'
The
print
statement isexecuted only if wemakeit pastboth conditionals, so we
can getthesameeffect with the
and
operator:
if 0 < x and x < 10:
print
'
x is a positive single-digit number.
'
57
36
Chapter3. Conditionalexecution
3.7 Catching exceptions using try and except
Earlierwesawacodesegmentwhereweusedthe
raw_input
and
int
functionsto
readandparseanintegernumberenteredbytheuser. Wealso sawhowtreacherous
doing thiscould be:
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int()
>>>
When we are executing these statements in the Python interpreter, we get a new
prompt from theinterpreter,think “oops”andmoveon to ournext statement.
Howeverif thiscodeis placed in aPython script and thiserroroccurs, your script
immediately stopsin itstracks with atraceback. It doesnot executethefollowing
statement.
Here is a sample program to convert a Fahrenheit temperature to a Celsius tem-
perature:
inp = raw_input(
'
Enter Fahrenheit Temperature:
'
)
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
Ifweexecutethis codeand give itinvalid input, it simply fails with an unfriendly
error message:
python fahren.py
Enter Fahrenheit Temperature:72
22.2222222222
python fahren.py
Enter Fahrenheit Temperature:fred
Traceback (most recent call last):
File "fahren.py", line 2, in <module>
fahr = float(inp)
ValueError: invalid literal for float(): fred
Thereisaconditionalexecution structurebuiltintoPython tohandlethesetypesof
expected andunexpected errorscalled“try/ except”. Theideaof
try
and
except
is that you know that some sequence of instruction(s) may have a problem and
you want to add some statements to be executed if an error occurs. These extra
statements(theexcept block)areignored ifthereis no error.
You can think of the
try
and
except
feature in Python as an “insurance policy”
on asequenceof statements.
Wecanrewriteour temperatureconverter as follows:
Documents you may be interested
Documents you may be interested