Python Programming: An Introduction to Computer Science

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

number = -1 # Startwith an illegal value to get into the loop.
while number < 0:
number = input("Entera positive number: ")
if number < 0:
print "Thenumber you entered was not positive"


Seehow thevaliditycheckgetsrepeatedintwo places?
Addinga warningtotheversionusingbreakonlyrequiresaddinganelsetotheexistingif.


while 1:
number = input("Entera positive number: ")
if x >= 0:
break # Exitloop if number is valid.
else:
print "Thenumber you entered was not positive"


8.5.2 Loopanda Half


Someprogrammerswouldsolve thewarningproblemfromtheprevioussectionusinga slightlydifferent
style.


while 1:
number = input("Entera positive number: ")
if x >= 0: break # Loop exit
print "The numberyou entered was not positive"


Heretheloopexitis actuallyinthemiddleoftheloopbody. Thisis calledaloopanda half. Somepurists
frownonexitsinthemidstofa looplike this,butthepatterncanbequitehandy.
Theloopanda halfis anelegantwaytoavoidtheprimingreadina sentinelloop.Hereis thegeneral
patternofa sentinelloopimplementedasa loopanda half.


while 1:
Get next data item
if the item is thesentinel: break
process the item


Figure8.3showsa flowchartofthisapproachtosentinelloops. Youcanseethatthisimplementationis
faithfultothefirstruleofsentinelloops:avoidprocessingthesentinelvalue.
Thechoiceofwhethertousebreakstatementsornotis largelya matteroftaste.Eitherstyleis accept-
able.Onetemptationthatshouldgenerallybeavoidedis pepperingthebodyofa loopwithmultiplebreak
statements.Thelogicofa loopis easilylostwhentherearemultipleexits.However, therearetimeswhen
eventhisruleshouldbebrokentoprovidethemostelegantsolutiontoa problem.


8.5.3 BooleanExpressionsasDecisions.


Sofar, wehave talkedaboutBooleanexpressionsonlywithinthecontextofothercontrolstructures.Some-
times,Booleanexpressionsthemselvescanactascontrolstructures. Infact,Booleanexpressionsareso
flexibleinPythonthatthey cansometimesleadtosubtleprogrammingerrors.
Considerwritinganinteractive loopthatkeepsgoingaslongastheuserresponsestartswitha “y.” To
allow theusertotypeeitheranupperorlowercaseresponse,youcouldusea looplike this:


while response[0] == "y" or response[0] == "Y":


Youmustbebecarefulnottoabbreviatethisconditionasyoumightthinkofit inEnglish:“Whilethefirst
letteris ’y’or’Y”’.Thefollowingformdoesnotwork.


while response[0] == "y" or "Y":

Free download pdf