Table Of ContentThink Python
How to Think Like a Computer Scientist
Version1.1.19
Think Python
How to Think Like a Computer Scientist
Version1.1.19
Allen Downey
Green Tea Press
Needham,Massachusetts
Copyright©2008AllenDowney.
Printinghistory:
April2002: FirsteditionofHowtoThinkLikeaComputerScientist.
August2007: Majorrevision,changedtitletoHowtoThinkLikea(Python)Programmer.
June2008: Majorrevision,changedtitletoThinkPython:HowtoThinkLikeaComputerScientist.
GreenTeaPress
9WashburnAve
NeedhamMA02492
Permissionisgrantedtocopy,distribute,and/ormodifythisdocumentunderthetermsoftheGNUFreeDoc-
umentation License, Version 1.1 or any later version published by the Free Software Foundation; with no
InvariantSections,noFront-CoverTexts,andwithnoBack-CoverTexts.
The GNU Free Documentation License is available from www.gnu.org or by writing to the Free Software
Foundation,Inc.,59TemplePlace,Suite330,Boston,MA02111-1307,USA.
TheoriginalformofthisbookisLATEXsourcecode. CompilingthisLATEXsourcehastheeffectofgenerating
adevice-independentrepresentationofatextbook,whichcanbeconvertedtootherformatsandprinted.
TheLATEXsourceforthisbookisavailablefromhttp://www.thinkpython.com
Preface
The strange history of this book
InJanuary1999IwaspreparingtoteachanintroductoryprogrammingclassinJava. Ihadtaught
it three times and I was getting frustrated. The failure rate in the class was too high and, even for
studentswhosucceeded,theoveralllevelofachievementwastoolow.
OneoftheproblemsIsawwasthebooks.Theyweretoobig,withtoomuchunnecessarydetailabout
Java,andnotenoughhigh-levelguidanceabouthowtoprogram. Andtheyallsufferedfromthetrap
dooreffect: theywouldstartouteasy,proceedgradually,andthensomewherearoundChapter5the
bottomwouldfallout. Thestudentswouldgettoomuchnewmaterial,toofast,andIwouldspend
therestofthesemesterpickingupthepieces.
Twoweeksbeforethefirstdayofclasses,Idecidedtowritemyownbook. Mygoalswere:
• Keepitshort. Itisbetterforstudentstoread10pagesthannotread50pages.
• Becarefulwithvocabulary. Itriedtominimizethejargonanddefineeachtermatfirstuse.
• Build gradually. To avoid trap doors, I took the most difficult topics and split them into a
seriesofsmallsteps.
• Focusonprogramming,nottheprogramminglanguage.Iincludedtheminimumusefulsubset
ofJavaandleftouttherest.
Ineededatitle,soonawhimIchoseHowtoThinkLikeaComputerScientist.
My first version was rough, but it worked. Students did the reading, and they understood enough
thatIcouldspendclasstimeonthehardtopics, theinterestingtopicsand(mostimportant)letting
thestudentspractice.
IreleasedthebookundertheGNUFreeDocumentationLicense,whichallowsuserstocopy,modify,
anddistributethebook.
Whathappenednextisthecoolpart.JeffElkner,ahighschoolteacherinVirginia,adoptedmybook
andtranslateditintoPython. Hesentmeacopyofhistranslation,andIhadtheunusualexperience
oflearningPythonbyreadingmyownbook.
Jeff and I revised the book, incorporated a case study by Chris Meyers, and in 2001 we released
How to Think Like a Computer Scientist: Learning with Python, also under the GNU Free Doc-
umentation License. As Green Tea Press, I published the book and started selling hard copies
throughAmazon.comandcollegebookstores. OtherbooksfromGreenTeaPressareavailableat
greenteapress.com.
vi Chapter0. Preface
In2003IstartedteachingatOlinCollegeandIgottoteachPythonforthefirsttime. Thecontrast
withJavawasstriking. Studentsstruggledless,learnedmore,workedonmoreinterestingprojects,
andgenerallyhadalotmorefun.
OverthelastfiveyearsIhavecontinuedtodevelopthebook,correctingerrors,improvingsomeof
theexamplesandaddingmaterial,especiallyexercises.In2008Istartedworkonamajorrevision—
atthesametime,IwascontactedbyaneditoratCambridgeUniversityPresswhowasinterestedin
publishingthenextedition. Goodtiming!
Theresultisthisbook,nowwiththelessgrandiosetitleThinkPython. Someofthechangesare:
• Iaddedasectionaboutdebuggingattheendofeachchapter. Thesesectionspresentgeneral
techniquesforfindingandavoidingbugs,andwarningsaboutPythonpitfalls.
• Iremovedthematerialinthelastfewchaptersabouttheimplementationoflistsandtrees. I
stilllovethosetopics,butIthoughttheywereincongruentwiththerestofthebook.
• Iaddedmoreexercises,rangingfromshorttestsofunderstandingtoafewsubstantialprojects.
• I added a series of case studies—longer examples with exercises, solutions, and discussion.
SomeofthemarebasedonSwampy,asuiteofPythonprogramsIwroteforuseinmyclasses.
Swampy,codeexamples,andsomesolutionsareavailablefromthinkpython.com.
• Iexpandedthediscussionofprogramdevelopmentplansandbasicdesignpatterns.
• The useof Python ismoreidiomatic. Thebook isstillabout programming, notPython, but
nowIthinkthebookgetsmoreleveragefromthelanguage.
Ihopeyouenjoyworkingwiththisbook,andthatithelpsyoulearntoprogramandthink,atleasta
littlebit,likeacomputerscientist.
AllenB.Downey
NeedhamMA
Allen Downey is an Associate Professor of Computer Science at the Franklin W. Olin College of
Engineering.
Acknowledgements
Firstandmostimportantly,IthankJeffElkner,whotranslatedmyJavabookintoPython,whichgot
thisprojectstartedandintroducedmetowhathasturnedouttobemyfavoritelanguage.
I also thank Chris Meyers, who contributed several sections to How to Think Like a Computer
Scientist.
And I thank the Free Software Foundation for developing the GNU Free Documentation License,
whichhelpedmakemycollaborationwithJeffandChrispossible.
IalsothanktheeditorsatLuluwhoworkedonHowtoThinkLikeaComputerScientist.
Ithankallthestudentswhoworkedwithearlierversionsofthisbookandallthecontributors(listed
below)whosentincorrectionsandsuggestions.
AndIthankmywife,Lisa,forherworkonthisbook,andGreenTeaPress,andeverythingelse,too.
vii
Contributor List
Morethan100sharp-eyedandthoughtfulreadershavesentinsuggestionsandcorrectionsoverthe
pastfewyears. Theircontributions,andenthusiasmforthisproject,havebeenahugehelp.
If you have a suggestion or correction, please send email to feedback@thinkpython.com. If I
makeachangebasedonyourfeedback,Iwilladdyoutothecontributorlist(unlessyouasktobe
omitted).
Ifyouincludeatleastpartofthesentencetheerrorappearsin,thatmakesiteasyformetosearch.
Pageandsectionnumbersarefine,too,butnotquiteaseasytoworkwith. Thanks!
• LloydHughAllensentinacorrectiontoSection8.4.
• YvonBouliannesentinacorrectionofasemanticerrorinChapter5.
• FredBremmersubmittedacorrectioninSection2.1.
• JonahCohenwrotethePerlscriptstoconverttheLaTeXsourceforthisbookintobeautifulHTML.
• MichaelConlonsentinagrammarcorrectioninChapter2andanimprovementinstyleinChapter1,
andheinitiateddiscussiononthetechnicalaspectsofinterpreters.
• BenoitGirardsentinacorrectiontoahumorousmistakeinSection5.6.
• CourtneyGleasonandKatherineSmithwrotehorsebet.py,whichwasusedasacasestudyinanearlier
versionofthebook.Theirprogramcannowbefoundonthewebsite.
• LeeHarrsubmittedmorecorrectionsthanwehaveroomtolisthere,andindeedheshouldbelistedas
oneoftheprincipaleditorsofthetext.
• JamesKaylinisastudentusingthetext.Hehassubmittednumerouscorrections.
• DavidKershawfixedthebrokencatTwicefunctioninSection3.10.
• EddieLamhassentinnumerouscorrectionstoChapters1,2,and3. HealsofixedtheMakefilesothat
itcreatesanindexthefirsttimeitisrunandhelpedussetupaversioningscheme.
• Man-YongLeesentinacorrectiontotheexamplecodeinSection2.4.
• DavidMayopointedoutthattheword“unconsciously”inChapter1neededtobechangedto“subcon-
sciously”.
• ChrisMcAloonsentinseveralcorrectionstoSections3.9and3.10.
• MatthewJ.Moelterhasbeenalong-timecontributorwhosentinnumerouscorrectionsandsuggestions
tothebook.
• SimonDiconMontfordreportedamissingfunctiondefinitionandseveraltyposinChapter3. Healso
founderrorsintheincrementfunctioninChapter13.
• JohnOuztscorrectedthedefinitionof“returnvalue”inChapter3.
• Kevin Parks sent in valuable comments and suggestions as to how to improve the distribution of the
book.
• DavidPoolsentinatypointheglossaryofChapter1,aswellaskindwordsofencouragement.
• MichaelSchmittsentinacorrectiontothechapteronfilesandexceptions.
• RobinShawpointedoutanerrorinSection13.1,wheretheprintTimefunctionwasusedinanexample
withoutbeingdefined.
• PaulSleighfoundanerrorinChapter7andabuginJonahCohen’sPerlscriptthatgeneratesHTML
fromLaTeX.
• CraigT.SnydalistestingthetextinacourseatDrewUniversity. Hehascontributedseveralvaluable
suggestionsandcorrections.
• IanThomasandhisstudentsareusingthetextinaprogrammingcourse. Theyarethefirstonestotest
thechaptersinthelatterhalfofthebook,andtheyhavemadenumerouscorrectionsandsuggestions.
viii Chapter0. Preface
• KeithVerheydensentinacorrectioninChapter3.
• PeterWinstanleyletusknowaboutalongstandingerrorinourLatininChapter3.
• ChrisWrobelmadecorrectionstothecodeinthechapteronfileI/Oandexceptions.
• MosheZadkahasmadeinvaluablecontributionstothisproject. Inadditiontowritingthefirstdraftof
thechapteronDictionaries,heprovidedcontinualguidanceintheearlystagesofthebook.
• ChristophZwerschkesentseveralcorrectionsandpedagogicsuggestions,andexplainedthedifference
betweengleichandselbe.
• JamesMayersentusawholeslewofspellingandtypographicalerrors,includingtwointhecontributor
list.
• HaydenMcAfeecaughtapotentiallyconfusinginconsistencybetweentwoexamples.
• AngelArnalispartofaninternationalteamoftranslatorsworkingontheSpanishversionofthetext.
HehasalsofoundseveralerrorsintheEnglishversion.
• TauhidulHoqueandLexBerezhnycreatedtheillustrationsinChapter1andimprovedmanyoftheother
illustrations.
• Dr. MicheleAlzettacaughtanerrorinChapter8andsentsomeinterestingpedagogiccommentsand
suggestionsaboutFibonacciandOldMaid.
• AndyMitchellcaughtatypoinChapter1andabrokenexampleinChapter2.
• KalinHarveysuggestedaclarificationinChapter7andcaughtsometypos.
• ChristopherP.SmithcaughtseveraltyposandishelpinguspreparetoupdatethebookforPython2.2.
• DavidHutchinscaughtatypointheForeword.
• Gregor Lingl is teaching Python at a high school in Vienna, Austria. He is working on a German
translationofthebook,andhecaughtacoupleofbaderrorsinChapter5.
• JuliePeterscaughtatypointhePreface.
• FlorinOprinasentinanimprovementinmakeTime,acorrectioninprintTime,andanicetypo.
• D.J.WebresuggestedaclarificationinChapter3.
• KenfoundafistfuloferrorsinChapters8,9and11.
• IvoWevercaughtatypoinChapter5andsuggestedaclarificationinChapter3.
• CurtisYankosuggestedaclarificationinChapter2.
• BenLogansentinanumberoftyposandproblemswithtranslatingthebookintoHTML.
• JasonArmstrongsawthemissingwordinChapter2.
• LouisCordiernoticedaspotinChapter16wherethecodedidn’tmatchthetext.
• BrianCainsuggestedseveralclarificationsinChapters2and3.
• RobBlacksentinapasselofcorrections,includingsomechangesforPython2.2.
• Jean-PhilippeReyatEcoleCentraleParissentanumberofpatches,includingsomeupdatesforPython
2.2andotherthoughtfulimprovements.
• JasonMaderatGeorgeWashingtonUniversitymadeanumberofusefulsuggestionsandcorrections.
• JanGundtofte-Bruunremindedusthat“aerror”isanerror.
• AbelDavidandAlexisDinnoremindedusthatthepluralof“matrix”is“matrices”,not“matrixes”.This
errorwasinthebookforyears,buttworeaderswiththesameinitialsreporteditonthesameday.Weird.
• CharlesThayerencouragedustogetridofthesemi-colonswehadputattheendsofsomestatements
andtocleanupouruseof“argument”and“parameter”.
• RogerSperbergpointedoutatwistedpieceoflogicinChapter3.
• SamBullpointedoutaconfusingparagraphinChapter2.
• AndrewCheungpointedouttwoinstancesof“usebeforedef.”
ix
• C.CoreyCapelspottedthemissingwordintheThirdTheoremofDebuggingandatypoinChapter4.
• AlessandrahelpedclearupsomeTurtleconfusion.
• WimChampagnefoundabrain-oinadictionaryexample.
• DouglasWrightpointedoutaproblemwithfloordivisioninarc.
• JaredSpindorfoundsomejetsamattheendofasentence.
• LinPeihengsentanumberofveryhelpfulsuggestions.
• RayHagtvedtsentintwoerrorsandanot-quite-error.
• TorstenHu¨bschpointedoutaninconsistencyinSwampy.
• IngaPetuhhovcorrectedanexampleinChapter14.
• ArneBabenhauserheidesentseveralhelpfulcorrections.
• MarkE.Casidaisisgoodatspottingrepeatedwords.
• ScottTylerfilledinathatwasmissing.Andthensentinaheapofcorrections.
• GordonShephardsentinseveralcorrections,allinseparateemails.
• AndrewTurnerspottedanerrorinChapter8.
• AdamHobartfixedaproblemwithfloordivisioninarc.
• Daryl Hammond and Sarah Zimmerman pointed out that I served up math.pi too early. And Zim
spottedatypo.
• GeorgeSassfoundabuginaDebuggingsection.
• BrianBinghamsuggestedExercise11.9.
• LeahEngelbert-FentonpointedoutthatIusedtupleasavariablename,contrarytomyownadvice.
Andthenfoundabunchoftyposanda“usebeforedef.”
• JoeFunkespottedatypo.
• Chao-chaoChenfoundaninconsistencyintheFibonacciexample.
• JeffPaineknowsthedifferencebetweenspaceandspam.
• LubosPintessentinatypo.
• GreggLindandAbigailHeithoffsuggestedExercise14.6.
• MaxHailperinhassentinanumberofcorrectionsandsuggestions. Maxisoneoftheauthorsofthe
extraordinaryConcreteAbstractions,whichyoumightwanttoreadwhenyouaredonewiththisbook.
• ChotipatPornavalaifoundanerrorinanerrormessage.
• StanislawAntolsentalistofveryhelpfulsuggestions.
• EricPashmansentanumberofcorrectionsforChapters4–11.
• MiguelAzevedofoundsometypos.
• JianhuaLiusentinalonglistofcorrections.
• NickKingfoundamissingword.
• MartinZuthersentalonglistofsuggestions.
• AdamZimmermanfoundaninconsistencyinmyinstanceofan“instance”andseveralothererrors.
• RatnakarTiwarisuggestedafootnoteexplainingdegeneratetriangles.
• Anurag Goel suggested another solution for is_abecedarian and sent some additional corrections.
AndheknowshowtospellJaneAusten.
• KelliKratzerspottedoneofthetypos.
• MarkGriffithspointedoutaconfusingexampleinChapter3.
• RoydanOngiefoundanerrorinmyNewton’smethod.
• PatrykWolowiechelpedmewithaproblemintheHTMLversion.
• MarkChonofskytoldmeaboutanewkeywordinPython3.0.
• RussellColemanhelpedmewithmygeometry.
• WeiHuangspottedseveraltypographicalerrors.
• KarenBarberspottedthetheoldesttypointhebook.
x Chapter0. Preface
Description:Python for Software Design is a concise introduction to software design using the Python programming language. Intended for people with no programming experience, this book starts with the most basic concepts and gradually adds new material. Some of the ideas students find most challenging, like rec