Python Programming: An Introduction to Computer Science

(Nora) #1
8.3.COMMONLOOPPATTERNS 123

The average of the numbersis 46.5


Inthisversion,theuserdoesn’t have tocountthedatavalues,buttheinterfaceis stillnotgood.Theuser
willalmostcertainlybeannoyedbytheconstantproddingformoredata.Theinteractive loophasmany good
applications;thisis notoneofthem.


8.3.2 SentinelLoops


Abettersolutiontothenumberaveragingproblemistoemploy a patterncommonlyknownasasentinel
loop. A sentinelloopcontinuestoprocessdatauntilreachinga specialvaluethatsignalstheend.Thespecial
valueiscalledthesentinel. Any valuemaybechosenforthesentinel. Theonlyrestrictionisthatit be
distinguishablefromactualdatavalues.Thesentinelis notprocessedaspartofthedata.
Hereis a generalpatternfordesigningsentinelloops:


get the first dataitem
while item is not the sentinel
process the item
get the next dataitem


Noticehow thispatternavoidsprocessingthesentinelitem.Thefirstitemis retrievedbeforetheloopstarts.
Thisis sometimescalledtheprimingread, asit getstheprocessstarted.If thefirstitemis thesentinel,the
loopimmediatelyterminatesandnodatais processed.Otherwise,theitemis processedandthenextoneis
read.Thelooptestat thetopensuresthisnext itemis notthesentinelbeforeprocessingit.Whenthesentinel
is reached,theloopterminates.
We canapplythesentinelpatterntoournumberaveragingproblem.Thefirststepis topicka sentinel.
Supposeweareusingtheprogramtoaverageexamscores.Inthatcase,wecansafelyassumethatnoscore
willbebelow 0.Theusercanentera negative numbertosignaltheendofthedata.Combiningthesentinel
loopwiththetwo accumulatorsfromtheinteractive loopversionyieldsthisprogram.


average3.py


def main():
sum = 0.0
count = 0
x = input("Entera number (negative to quit) >> ")
while x >= 0:
sum = sum + x
count = count+ 1
x = input("Entera number (negative to quit) >> ")
print "\nThe averageof the numbers is", sum / count


I have changedthepromptsothattheuserknowshow tosignaltheendofthedata.Noticethatthepromptis
identicalat theprimingreadandthebottomoftheloopbody.
Now wehave a usefulformoftheprogram.Hereit is inaction:


Enter a number (negativeto quit) >> 32
Enter a number (negativeto quit) >> 45
Enter a number (negativeto quit) >> 34
Enter a number (negativeto quit) >> 76
Enter a number (negativeto quit) >> 45
Enter a number (negativeto quit) >> -1


The average of the numbersis 46.4


Thisversionprovidestheeaseofuseoftheinteractive loopwithoutthehassleofhavingtotype“yes”allthe
time.Thesentinelloopis a veryhandypatternforsolvingallsortsofdataprocessingproblems.It’s another
cliche that ́ youshouldcommittomemory.

Free download pdf