Python Programming: An Introduction to Computer Science

(Nora) #1

Chapter 8


Control Structures, Part 2


InChapter7, welookedin detailat thePythonifstatementanditsusein implementingdesignpatternssuch
asone-way, two-wayandmulti-waydecisions.Inthischapter, we’ll wrapupourtourofcontrolstructures
witha detailedlookat loopsandBooleanexpressions.


8.1 ForLoops:A QuickReview


YoualreadyknowthatthePythonforstatementprovidesa kindofloop.It allowsustoiteratethrougha
sequenceofvalues.


for in :



Theloopindex variablevartakesoneachsuccessive valueinthesequence,andthestatementsinthebody
oftheloopareexecutedonceforeachvalue.
Supposewewanttowritea programthatcancomputetheaverageofa seriesofnumbersenteredbythe
user. To make theprogramgeneral,it shouldworkforany sizesetofnumbers.Youknow thatanaverage
is calculatedbysummingupthenumbersanddividingbythecountofhowmany numbersthereare.We
don’t needtokeeptrackofallthenumbersthathave beenentered;wejustneeda runningsumsothatwecan
calculatetheaverageat theend.
Thisproblemdescriptionshouldstartsomebellsringinginyourhead.It suggeststheuseofsomedesign
patternsyouhave seenbefore.We aredealingwitha seriesofnumbers—thatwillbehandledbysomeform
ofloop.If therearennumbers,theloopshouldexecutentimes;wecanusethecountedlooppattern.We
alsoneeda runningsum;thatcallsfora loopaccumulator. Puttingthetwo ideastogether, wecangeneratea
designforthisproblem.


Input the count of thenumbers, n
Initialize sum to 0
Loop n times
Input a number,x
Add x to sum
Output average as sum / n


Hopefully, youseeboththecountedloopandaccumulatorpatternsintegratedintothisdesign.
We cantranslatethisdesignalmostdirectlyintoa Pythonimplementation.


average1.py


def main():
n = input("Howmany numbers do you have? ")
sum = 0.0
for i in range(n):


119
Free download pdf