Python Programming: An Introduction to Computer Science

(Nora) #1
8.4.COMPUTINGWITHBOOLEANS 129

scoreA == 15 or scoreB== 15


Wheneitherscorereaches15,oneofthetwo simpleconditionsbecomestrue,and,bydefinitionofor, the
entireBooleanexpressionis true.Aslongasbothconditionsremainfalse(neitherplayerhasreached15)the
entireexpressionis false.
Oursimulationwillneeda loopthatcontinuesaslongasthegameisnotover. We canconstructan
appropriateloopconditionbytakingthenegationofthegame-over condition:


while not (scoreA == 15 or scoreB== 15):


continue playing


We canalsoconstructmorecomplex Booleanexpressionsthatreflectdifferentpossiblestoppingcondi-
tions.Someracquetballplayersplayshutouts(sometimescalleda skunk). Fortheseplayers,a gamealso
endswhenoneoftheplayersreaches7 andtheotherhasnotyetscoreda point.Forbrevity, I’ll useafor
scoreAandbforscoreB. Hereis anexpressionforgame-over whenshutoutsareincluded:


a == 15 or b == 15 or (a == 7 and b == 0) or (b == 7 and a == 0)


DoyouseehowI have addedtwo moresituationstotheoriginalcondition?Thenewpartsreflectthetwo
possiblewaysa shutoutcanoccur, andeachrequirescheckingbothscores.Theresultis a fairlycomplex
expression.
Whilewe’re at it,let’s tryonemoreexample.Supposewewerewritinga simulationforvolleyball,rather
thanracquetball.Volleyballdoesnothave shutouts,butit requiresa teamtowinbyat leasttwo points.If the
scoreis 15to14,oreven 21 to20,thegamecontinues.
Let’s writea conditionthatcomputeswhena volleyballgameis over. Here’s oneapproach.


(a >= 15 and a - b >= 2) or (b >= 15 and b - a >= 2)


Doyouseehow thisexpressionworks?It basicallysaysthegameis overwhenteamAhaswon(scoredat
least 15 andleadingbyat least2)orwhenteamB haswon.
Hereis anotherwaytodoit.


(a >= 15 or b >= 15) and abs(a - b) >= 2


Thisversionisa bitmoresuccinct. It statesthatthegameisoverwhenoneoftheteamshasreacheda
winningtotalandthedifferenceinthescoresis at least2.Rememberthatabsreturnstheabsolutevalueof
anexpression.


8.4.2 BooleanAlgebra


AlldecisionsincomputerprogramsboildowntoappropriateBooleanexpressions.Theabilitytoformulate,
manipulateandreasonwiththeseexpressionsis animportantskillforprogrammersandcomputerscientists.
Booleanexpressionsobey certainalgebraiclawssimilartothosethatapplytonumericoperations. These
lawsarecalledBooleanlogicorBooleanalgebra.
Let’s lookata fewexamples.Thefollowingtableshowssomerulesofalgebrawiththeircorrelatesin
Booleanalgebra.


Algebra Booleanalgebra
a 0 0 aandfalse==false
a 1 a aandtrue==a
a 0 a aorfalse==a

Fromtheseexamples,youcanseethatandhassimilaritiestomultiplication,andorhassimilaritiesto
addition;while0 and1 correspondtofalseandtrue.
HerearesomeotherinterestingpropertiesofBooleanoperations.Anythingoredwithtrueis justtrue.


a or true == true


Bothandandordistributeovereachother.

Free download pdf