Python Programming: An Introduction to Computer Science

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

Recallthatthepreviousversionoftheprogramforcedtheusertocountuphow many numberstherewere
tobeaveraged.We wanttomodifytheprogramsothatit keepstrackofhow many numbersthereare.We
candothiswithanotheraccumulator, callitcount, thatstartsat zeroandincreasesby1 eachtimethrough
theloop.
To allowtheusertostopatany time,eachiterationoftheloopwillaskwhetherthereis moredatato
process.Thegeneralpatternforaninteractive looplookslike this:


set moredata to "yes"
while moredata is "yes"
get the next dataitem
process the item
ask user if thereis moredata


Combiningtheinteractive looppatternwithaccumulatorsforthesumandcountyieldsthisalgorithmfor
theaveragingprogram.


initialize sum to 0.0
initialize count to 0
set moredata to "yes"
while moredata is "yes"
input a number,x
add x to sum
add 1 to count
ask user if thereis moredata
output sum / count


Noticehow thetwo accumulatorsareinterleavedintothebasicstructureoftheinteractive loop.
Hereis thecorrespondingPythonprogram:


average2.py


def main():
sum = 0.0
count = 0
moredata = "yes"
while moredata[0]== "y":
x = input("Entera number >> ")
sum = sum + x
count = count+ 1
moredata = raw_input("Doyou have more numbers (yes or no)?")
print "\nThe averageof the numbers is", sum / count


Noticethisprogramusesstringindexing(moredata[0]) tolookjustatthefirstletteroftheuser’s input.
Thisallowsforvariedresponsessuchas“yes,” “y,” “yeah,” etc.Allthatmattersis thatthefirstletteris a “y.”
Alsonotetheuseofrawinputtogetthisvalue.Rememberyoushoulduserawinputto getstringdata.
Hereis sampleoutputfromthisprogram.


Enter a number >> 32
Do you have more numbers(yes or no)? yes
Enter a number >> 45
Do you have more numbers(yes or no)? y
Enter a number >> 34
Do you have more numbers(yes or no)? y
Enter a number >> 76
Do you have more numbers(yes or no)? y
Enter a number >> 45
Do you have more numbers(yes or no)? nope

Free download pdf