Python Programming: An Introduction to Computer Science

(Nora) #1

Chapter 11


Data Collections


Asyousaw inthelastchapter, classesareonemechanismforstructuringthedatainourprograms.Classes
alone,however, arenotenoughtosatisfyallofourdata-handlingneeds.
If youthinkaboutthekindsofdatathatmostreal-worldprogramsmanipulate,youwillquicklyrealize
thatmany programsdealwithlargecollectionsofsimilarinformation.A few examplesofthecollectionsthat
youmightfindina modernprograminclude


 Wordsina document.

 Studentsina course.

 Datafromanexperiment.

 Customersofa business.

 Graphicsobjectsdrawnonthescreen.

 Cardsina deck.

Inthischapter, youwilllearntechniquesforwritingprogramsthatmanipulatecollectionslike these.


11.1 ExampleProblem:SimpleStatistics


BackinChapter8, wewrotea simplebutusefulprogramtocomputethemean(average)ofa setofnumbers
enteredbytheuser. Justtorefreshyourmemory(asif youcouldforgetit),hereis theprogramagain:


average4.py


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


main()


Thisprogramallowstheusertoentera sequenceofnumbers,buttheprogramitselfdoesnotkeeptrack
ofwhatnumberswereentered.Instead,it justkeepsa summaryofthenumbersintheformofa runningsum.
That’s allthat’s neededtocomputethemean.


177
Free download pdf