Python Programming: An Introduction to Computer Science

(Nora) #1
8.4.COMPUTINGWITHBOOLEANS 127

# update sum and countfor values in line
for xStr in string.split(line):
sum = sum + eval(xStr)
count = count+ 1
line = infile.readline()
print "\nThe averageof the numbers is", sum / count

Asyoucansee,theloopthatprocessesthenumbersina lineis indentedinsideofthefileprocessingloop.
Theouterwhileloopiteratesonceforeachlineofthefile.Oneachiterationoftheouterloop,theinner
forloopiteratesasmany timesastherearenumbersonthatline.Whentheinnerloopfinishes,thenext line
ofthefileis read,andtheouterloopgoesthroughitsnextiteration.
Theindividualfragmentsofthisproblemarenotcomplex whentakenseparately, butthefinalresultis
fairlyintricate.Thebestwaytodesignnestedloopsis tofollowtheprocesswedidhere.Firstdesignthe
outerloopwithoutworryingaboutwhatgoesinside.Thendesignwhatgoesinside,ignoringtheouterloop(s).
Finally, putthepiecestogether, takingcaretopreserve thenesting. If theindividualloopsarecorrect,the
nestedresultwillworkjustfine;trustit.Witha littlepractice,you’ll beimplementingdouble-,eventriple-
nestedloopswithease.


8.4 ComputingwithBooleans


We nowhave two controlstructures,ifandwhile, thatuseconditions,whichareBooleanexpressions.
Conceptually, a Booleanexpressionevaluatestooneoftwo values:falseortrue.InPython,thesevaluesare
representedbytheints0 and1.Sofar, wehave usedsimpleBooleanexpressionsthatcomparetwo values
(e.g.,while x >= 0).


8.4.1 BooleanOperators


Sometimesthesimpleconditionsthatwehave beenusingdonotseemexpressive enough.Forexample,
supposeyouneedtodeterminewhethertwo pointobjectsareinthesameposition—thatis,they have equalx
coordinatesandequalycoordinates.Onewayofhandlingthiswouldbea nesteddecision.


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


points are the same


else:


points are different


else:


points are different


Youcanseehow awkwardthisis.
Insteadofworkingaroundthisproblemwitha decisionstructure,anotherapproachwouldbetoconstruct
a morecomplex expressionusingBooleanoperations. Like mostprogramminglanguages,Pythonprovides
threeBooleanoperators: and,orandnot. Let’s take a lookat thesethreeoperatorsandthenseehow they
canbeusedtosimplifyourproblem.
TheBooleanoperatorsandandorareusedto combinetwo Booleanexpressionsandproducea Boolean
result.


and
or

Theandoftwo expressionsistrueexactlywhenbothoftheexpressionsaretrue. We canrepresentthis
definitioninatruthtable.

Free download pdf