Python Programming: An Introduction to Computer Science

(Nora) #1
128 CHAPTER8. CONTROLSTRUCTURES,PART 2

P Q PandQ
T T T
T F F
F T F
F F F

Inthistable,PandQrepresentsmallerBooleanexpressions.Sinceeachexpressionhastwo possiblevalues,
therearefourpossiblecombinationsofvalues,eachshownasonerow inthetable.Thelastcolumngivesthe
valueofPandQforeachpossiblecombination.Bydefinition,theandis trueonlyinthecasewhereboth
PandQaretrue.
Theoroftwo expressionsis truewheneitherexpressionis true.Hereis thetruthtabledefining or:


P Q PorQ
T T T
T F T
F T T
F F F

Theonlytimetheoris falseis whenbothexpressionsarefalse.Noticeespeciallythatoris truewhenboth
expressionsaretrue.Thisis themathematicaldefinitionofor, buttheword“or”is sometimesusedinan
exclusive senseineverydayEnglish.If yourmomsaidthatyoucouldhave cake orcookiesfordessert,she
wouldprobablyscoldyoufortakingboth.
Thenotoperatorcomputestheoppositeofa Booleanexpression.It is aunaryoperator, meaningthatit
operatesona singleexpression.Thetruthtableis verysimple.


P notP
T F
F T

UsingBooleanoperators,it is possibletobuildarbitrarilycomplex Booleanexpressions.Aswitharith-
meticoperators,theexactmeaningofa complex expressiondependsontheprecedencerulesfortheoperators.
Considerthisexpression.


a or not b and c


How shouldthisbeevaluated?
Pythonfollowsa standardconventionthattheorderofprecedenceisnot, followedbyand, followedby
or. Sotheexpressionwouldbeequivalenttothisparenthesizedversion.


(a or ((not b) and c))


Unlike arithmetic,however, mostpeopledon’t tendtoknow orremembertheprecedencerulesforBooleans.
I suggestthatyoualwaysparenthesizeyourcomplex expressionstopreventconfusion.
Nowthatwehave someBooleanoperators,wearereadytoreturntoourexampleproblem.To testfor
theco-locationoftwo points,wecoulduseanandoperation.


if p1.getX() == p2.getX()and p2.getY() == p1.getY():


points are the same


else:


points are different


Heretheentireexpressionwillonlybetruewhenbothofthesimpleconditionsaretrue.Thisensuresthat
boththexandycoordinateshave tomatchforthepointstobethesame.Obviously, thisis muchsimplerand
clearerthanthenestedifs fromthepreviousversion.
Let’s lookat a slightlymorecomplex example.Inthenextchapter, wewilldevelopa simulationforthe
gameofracquetball.Partofthesimulationwillneedtodeterminewhena gamehasended. Supposethat
scoreAandscoreBrepresentthescoresoftwo racquetballplayers.Thegameis overassoonaseitherof
theplayershasreached 15 points.Hereis a Booleanexpressionthatis truewhenthegameis over:

Free download pdf