126 CHAPTER8. CONTROLSTRUCTURES,PART 2
line = infile.readline()
while line != "":
sum = sum + eval(line)
count = count+ 1
line = infile.readline()
print "\nThe averageof the numbers is", sum / count
Obviously, thisversionis notquiteasconciseastheversionusingreadlinesandaforloop.If the
filesizesareknowntoberelativelymodest,thatapproachis probablybetter. Whenfilesizesarequitelarge,
however, anend-of-fileloopis invaluable.
8.3.4 NestedLoops.
Inthelastchapter, yousawhowcontrolstructuressuchasdecisionsandloopscouldbenestedinsideone
anothertoproducesophisticatedalgorithms.Oneparticularlyuseful,butsomewhattricky techniqueis the
nestingofloops.
Let’s take a lookat anexampleprogram.How aboutonelastversionofournumberaveragingproblem?
Honest,I promisethisis thelasttimeI’ll usethisexample.^1 Supposewemodifythespecificationofourfile
averagingproblemslightly. Thistime,insteadoftypingthenumbersintothefileone-per-line,we’ll allow
any numberofvaluesona line.Whenmultiplevaluesappearona line,they willbeseparatedbycommas.
Atthetoplevel,thebasicalgorithmwillbesomesortoffile-processingloopthatcomputesa running
sumandcount.Forpractice,let’s useanend-of-fileloop.Hereis thecodecomprisingthetop-level loop.
sum = 0.0
count = 0
line = infile.readline()
while line != "":
update sum and countfor values in line
line = infile.readline()
print "\nThe averageof the numbers is", sum / count
Nowweneedtofigureouthowtoupdatethesumandcountinthebodyoftheloop. Sinceeach
individuallineofthefilecontainsoneormorenumbersseparatedbycommas,wecansplitthelineinto
substrings,eachofwhichrepresentsa number. Thenweneedtoloopthroughthesesubstrings,converteach
toa number, andaddit tosum. We alsoneedtoadd1 tocountforeachnumber. Hereis a codefragment
thatprocessesa line:
for xStr in string.split(line,","):
sum = sum + eval(xStr)
count = count +1
Noticethattheiterationoftheforloopinthisfragmentiscontrolledbythevalueofline, whichjust
happenstobetheloop-controlvariableforthefile-processingloopweoutlinedabove.
Knittingthesetwo loopstogether, hereis ourprogram.
average7.py
import string
def main():
fileName = raw_input("Whatfile are the numbers in? ")
infile = open(fileName,’r’)
sum = 0.0
count = 0
line = infile.readline()
while line != "":
(^1) untilChapter11...