7.1.SIMPLEDECISIONS 103
Thebodyis justa sequenceofoneormorestatementsindentedundertheifheading.Inconvert2.py
therearetwoifstatements,bothofwhichhave a singlestatementinthebody.
Thesemanticsoftheifshouldbeclearfromtheexampleabove.First,theconditionintheheading
is evaluated.If theconditionis true,thesequenceofstatementsinthebodyis executed,andthencontrol
passestothenextstatementintheprogram.If theconditionis false,thestatementsinthebodyareskipped.
Figure7.2showsthesemanticsoftheifasa flowchart. Noticethatthebodyoftheifeitherexecutesor
yes
no
<condition> true?
<Body>
Figure7.2:Controlflow ofsimpleif-statement
notdependingonthecondition.Ineithercase,controlthenpassestothenextstatementaftertheif. Thisis
aone-wayorsimpledecision.
7.1.2 FormingSimpleConditions
Onepointthathasnotyetbeendiscussedisexactlywhata conditionlookslike.Forthetimebeing,our
programswillusesimpleconditionsthatcomparethevaluesoftwo expressions.
than”or“equalto.” TherearesixrelationaloperatorsinPython,showninthefollowingtable.
Python Mathematics Meaning
Lessthan
Lessthanorequalto
Equalto
Greaterthanorequalto
Greaterthan
! Notequalto
Noticeespeciallytheuseof forequality. SincePythonusesthe signtoindicateanassignmentstate-
ment,a differentsymbolis requiredfortheconceptofequality. Acommonmistake inPythonprogramsis
using inconditions,wherea is required.
Conditionsmaycompareeithernumbersorstrings. Whencomparingstrings,theorderingislexico-
graphic. Basically, thismeansthatstringsareputinalphabeticorderaccordingtotheunderlyingASCII
codes.Soallupper-caseletterscomebeforelowercaseletters(e.g.,“Bbbb”comesbefore“aaaa”,since“B”
precedes“a”).
I shouldmentionthatconditionsareactuallya typeofexpression,calledaBooleanexpression,after
GeorgeBoole,a 19thcenturyEnglishmathematician. Whena Booleanexpressionis evaluated,it produces
a valueofeithertrue(theconditionholds)orfalse(itdoesnothold).InPython,conditionsreturnintvalues.
A trueconditionproducesa 1, whilea falseconditionproducesa 0.Herearea few examples: