120 CHAPTER8. CONTROLSTRUCTURES,PART 2
x = input("Entera number >> ")
sum = sum + x
print "\nThe averageof the numbers is", sum / n
Therunningsumstartsat0,andeachnumberis addedinturn.Noticethatsumis initializedtoa float0.0.
Thisensuresthatthedivisionsum / nonthelastlinereturnsa floatevenif alltheinputvalueswereints.
Hereis theprograminaction.
How many numbers do youhave? 5
Enter a number >> 32
Enter a number >> 45
Enter a number >> 34
Enter a number >> 76
Enter a number >> 45
The average of the numbersis 46.4
Well,thatwasn’t toobad. Knowinga coupleofcommonpatterns,countedloopandaccumulator, got
ustoa workingprogramwithminimaldifficultyindesignandimplementation.Hopefully, youcanseethe
worthofcommittingthesesortsofprogrammingclich ́estomemory.
8.2 IndefiniteLoops.
Ouraveragingprogramis certainlyfunctional,butit doesn’t have thebestuserinterface.It beginsbyasking
theuserhow many numbersthereare.Fora handfulofnumbersthisis OK,butwhatif I have a wholepage
ofnumberstoaverage?It mightbea significantburdentogothroughandcountthemup.
It wouldbemuchnicerif thecomputercouldtake careofcountingthenumbersforus.Unfortunately, as
younodoubtrecall,theforloopis a definiteloop,andthatmeansthenumberofiterationsis determined
whentheloopstarts.We can’t usea definiteloopunlessweknow thenumberofiterationsaheadoftime,and
wecan’t know how many iterationsthisloopneedsuntilallofthenumbershave beenentered.We seemto
bestuck.
Thesolutiontothisdilemmaliesinanotherkindofloop,theindefiniteorconditionalloop. Anindefinite
loopkeepsiteratinguntilcertainconditionsaremet.Thereis noguaranteeaheadoftimeregardinghow many
timestheloopwillgoaround.
InPython,anindefiniteloopis implementedusingawhilestatement.Syntactically, thewhileis very
simple.
while
Hereconditionis a Booleanexpression,justlike inifstatements.Thebodyis,asusual,a sequenceof
oneormorestatements.
Thesemanticsofwhileisstraightforward. Thebodyoftheloopexecutesrepeatedlyaslongasthe
conditionremainstrue.Whentheconditionis false,theloopterminates.Figure8.1showsa flowchartforthe
while. Noticethattheconditionis alwaystestedatthetopoftheloop,beforetheloopbodyis executed.
Thiskindofstructureis calledapre-testloop.If theloopconditionis initiallyfalse,theloopbodywillnot
executeat all.
Hereis anexampleofa simplewhileloopthatcountsfrom0 to10:
i = 0
while i <= 10:
print i
i = i + 1
Thiscodewillhave thesameoutputasif wehadwrittenaforlooplike this: