Python Programming: An Introduction to Computer Science

(Nora) #1
8.5.OTHERCOMMONSTRUCTURES 133

no

yes

Process the item

Item is the sentinel?

Get next Data item

Figure8.3:Loop-and-a-halfimplementationofsentinellooppattern

Infact,thisis aninfiniteloop.Understandingwhythisconditionis alwaystruerequiresdiggingintosome
idiosyncrasiesofPythonBooleanexpressions.
Youalreadyknow thatPythondoesnothave any specialBooleantype.We have beenusingtheintvalues
0 and1 torepresenttheBooleanvaluesfalseandtrue,respectively. ThePythonconditionoperators(i.e.,
==) alwaysevaluatetoeither0 or1.However, Pythonis actuallyveryflexibleaboutwhatcanbea Boolean
expression.Any built-intypecanbeinterpretedasa Boolean.Fornumbers(ints,floatsandlongints)a zero
valueis consideredasfalse,anythingotherthanzerois takenastrue.Othertypescanalsobeusedin Boolean
expressions.Forexample,Pythoninterpretsanemptystringasfalseandany nonemptystringastrue.
TheflexibilityofPythonBooleansextendstotheBooleanoperators. Althoughthemainuseofthese
operatorsis formingBooleanexpressions,they have operationaldefinitionsthatmake themusefulforother
purposesaswell.Thistablesummarizesthebehavioroftheseoperators.


operator operationaldefinition
xandy Ifxis false,returnx. Otherwise,returny.
xory Ifxis false,returny. Otherwise,returnx.
notx Ifxis false,return1.Otherwise,return0.

Thedefinitionofnotisstraightforward. It mighttake a bitofthinkingtoconvinceyourselfthatthese
descriptionsofandandorfaithfullyreflectthetruthtablesyousaw at thebeginningofthechapter.
Considertheexpressionxandy. Inorderforthistobetrue,bothexpressionsxandymustbetrue.As
soonasoneofthemis discoveredtobefalse,thepartyis over. Pythonlooksat theexpressionsleft-to-right.
Ifxis false,Pythonshouldreturna falseresult.Whateverthefalsevalueofxwas,thatis whatis returned.
Ifxturnsouttobetrue,thenthetruthorfalsityofthewholeexpressionturnsontheresultofy. Simply
returningyguaranteesthatifyistrue,thewholeresultistrue,andifyisfalse,thewholeresultisfalse.
Similarreasoningcanbeusedtoshowthatthedescriptionoforis faithfultothelogicaldefinitionofor
giveninthetruthtable.
TheseoperationaldefinitionsshowthatPython’s Booleanoperatorsareshort-circuitoperators. That
meansthata trueorfalsevalueis returnedassoonastheresultis known.Inanandwherethefirstexpression
is falseandinanorwherethefirstexpressionis true,Pythonwillnotevenevaluatethesecondexpression.
Now let’s take a lookat ourinfiniteloopproblem.

Free download pdf