ebook img

Think Python: How to Think Like a Computer Scientist PDF

2012·0.84 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Think Python: How to Think Like a Computer Scientist

Think Python How to Think Like a Computer Scientist Version2.0.1 June2012 Think Python How to Think Like a Computer Scientist Version2.0.1 June2012 Allen Downey Green Tea Press Needham,Massachusetts Copyright©2012AllenDowney. GreenTeaPress 9WashburnAve NeedhamMA02492 Permission is granted to copy, distribute, and/or modify this document under the terms of the CreativeCommonsAttribution-NonCommercial3.0UnportedLicense,whichisavailableathttp: //creativecommons.org/licenses/by-nc/3.0/. TheoriginalformofthisbookisLATEXsourcecode.CompilingthisLATEXsourcehastheeffectofgen- eratingadevice-independentrepresentationofatextbook,whichcanbeconvertedtootherformats andprinted. TheLATEXsourceforthisbookisavailablefromhttp://www.thinkpython.com Preface The strange history of this book InJanuary1999IwaspreparingtoteachanintroductoryprogrammingclassinJava. Ihad taughtitthreetimesandIwasgettingfrustrated. Thefailurerateintheclasswastoohigh and,evenforstudentswhosucceeded,theoveralllevelofachievementwastoolow. OneoftheproblemsIsawwasthebooks. Theyweretoobig,withtoomuchunnecessary detailaboutJava,andnotenoughhigh-levelguidanceabouthowtoprogram.Andtheyall sufferedfromthetrapdooreffect: theywouldstartouteasy,proceedgradually,andthen somewherearoundChapter5thebottomwouldfallout.Thestudentswouldgettoomuch newmaterial,toofast,andIwouldspendtherestofthesemesterpickingupthepieces. Twoweeksbeforethefirstdayofclasses,Idecidedtowritemyownbook. Mygoalswere: • Keepitshort. Itisbetterforstudentstoread10pagesthannotread50pages. • Be careful with vocabulary. I tried to minimize the jargon and define each term at firstuse. • Buildgradually. Toavoidtrapdoors, Itookthemostdifficulttopicsandsplitthem intoaseriesofsmallsteps. • Focus on programming, not the programming language. I included the minimum usefulsubsetofJavaandleftouttherest. Ineededatitle,soonawhimIchoseHowtoThinkLikeaComputerScientist. Myfirstversionwasrough,butitworked. Studentsdidthereading,andtheyunderstood enough that I could spend class time on the hard topics, the interesting topics and (most important)lettingthestudentspractice. I released the book under the GNU Free Documentation License, which allows users to copy,modify,anddistributethebook. Whathappenednextisthecoolpart. JeffElkner,ahighschoolteacherinVirginia,adopted mybookandtranslateditintoPython. Hesentmeacopyofhistranslation,andIhadthe unusual experience of learning Python by reading my own book. As Green Tea Press, I publishedthefirstPythonversionin2001. In2003IstartedteachingatOlinCollegeandIgottoteachPythonforthefirsttime. The contrast with Java was striking. Students struggled less, learned more, worked on more interestingprojects,andgenerallyhadalotmorefun. vi Chapter0. Preface OverthelastnineyearsIcontinuedtodevelopthebook,correctingerrors,improvingsome oftheexamplesandaddingmaterial,especiallyexercises. Theresultisthisbook,nowwiththelessgrandiosetitleThinkPython. Someofthechanges are: • Iaddedasectionaboutdebuggingattheendofeachchapter. Thesesectionspresent general techniques for finding and avoiding bugs, and warnings about Python pit- falls. • Iaddedmoreexercises,rangingfromshorttestsofunderstandingtoafewsubstantial projects. AndIwrotesolutionsformostofthem. • I added a series of case studies—longer examples with exercises, solutions, and discussion. Some are based on Swampy, a suite of Python programs I wrote for use in my classes. Swampy, code examples, and some solutions are available from http://thinkpython.com. • Iexpandedthediscussionofprogramdevelopmentplansandbasicdesignpatterns. • I added appendices about debugging, analysis of algorithms, and UML diagrams withLumpy. Ihopeyouenjoyworkingwiththisbook,andthatithelpsyoulearntoprogramandthink, atleastalittlebit,likeacomputerscientist. AllenB.Downey NeedhamMA AllenDowneyisaProfessorofComputerScienceattheFranklinW.OlinCollegeofEngi- neering. Acknowledgments Many thanks to Jeff Elkner, who translated my Java book into Python, which got this projectstartedandintroducedmetowhathasturnedouttobemyfavoritelanguage. ThanksalsotoChrisMeyers,whocontributedseveralsectionstoHowtoThinkLikeaCom- puterScientist. ThankstotheFreeSoftwareFoundationfordevelopingtheGNUFreeDocumentationLi- cense, which helped make my collaboration with Jeff and Chris possible, and Creative CommonsforthelicenseIamusingnow. ThankstotheeditorsatLuluwhoworkedonHowtoThinkLikeaComputerScientist. Thankstoallthestudentswhoworkedwithearlierversionsofthisbookandallthecon- tributors(listedbelow)whosentincorrectionsandsuggestions. vii Contributor List Morethan100sharp-eyedandthoughtfulreadershavesentinsuggestionsandcorrections overthepastfewyears. Theircontributions,andenthusiasmforthisproject,havebeena hugehelp. Ifyouhaveasuggestionorcorrection, [email protected]. If I make a change based on your feedback, I will add you to the contributor list (unless youasktobeomitted). Ifyouincludeatleastpartofthesentencetheerrorappearsin,thatmakesiteasyformeto search. Pageandsectionnumbersarefine,too,butnotquiteaseasytoworkwith. Thanks! • LloydHughAllensentinacorrectiontoSection8.4. • YvonBouliannesentinacorrectionofasemanticerrorinChapter5. • FredBremmersubmittedacorrectioninSection2.1. • Jonah Cohen wrote the Perl scripts to convert the LaTeX source for this book into beautiful HTML. • Michael Conlon sent in a grammar correction in Chapter 2 and an improvement in style in Chapter1,andheinitiateddiscussiononthetechnicalaspectsofinterpreters. • BenoitGirardsentinacorrectiontoahumorousmistakeinSection5.6. • CourtneyGleasonandKatherineSmithwrotehorsebet.py,whichwasusedasacasestudy inanearlierversionofthebook.Theirprogramcannowbefoundonthewebsite. • LeeHarrsubmittedmorecorrectionsthanwehaveroomtolisthere,andindeedheshouldbe listedasoneoftheprincipaleditorsofthetext. • JamesKaylinisastudentusingthetext.Hehassubmittednumerouscorrections. • DavidKershawfixedthebrokencatTwicefunctioninSection3.10. • EddieLamhassentinnumerouscorrectionstoChapters1,2,and3.HealsofixedtheMakefile sothatitcreatesanindexthefirsttimeitisrunandhelpedussetupaversioningscheme. • Man-YongLeesentinacorrectiontotheexamplecodeinSection2.4. • DavidMayopointedoutthattheword“unconsciously"inChapter1neededtobechangedto “subconsciously". • ChrisMcAloonsentinseveralcorrectionstoSections3.9and3.10. • MatthewJ.Moelterhasbeenalong-timecontributorwhosentinnumerouscorrectionsand suggestionstothebook. • SimonDiconMontfordreportedamissingfunctiondefinitionandseveraltyposinChapter3. HealsofounderrorsintheincrementfunctioninChapter13. • JohnOuztscorrectedthedefinitionof“returnvalue"inChapter3. • KevinParkssentinvaluablecommentsandsuggestionsastohowtoimprovethedistribution ofthebook. • DavidPoolsentinatypointheglossaryofChapter1,aswellaskindwordsofencouragement. • MichaelSchmittsentinacorrectiontothechapteronfilesandexceptions. viii Chapter0. Preface • RobinShawpointedoutanerrorinSection13.1,wheretheprintTimefunctionwasusedinan examplewithoutbeingdefined. • PaulSleighfoundanerrorinChapter7andabuginJonahCohen’sPerlscriptthatgenerates HTMLfromLaTeX. • CraigT.SnydalistestingthetextinacourseatDrewUniversity. Hehascontributedseveral valuablesuggestionsandcorrections. • IanThomasandhisstudentsareusingthetextinaprogrammingcourse.Theyarethefirstones totestthechaptersinthelatterhalfofthebook,andtheyhavemadenumerouscorrectionsand suggestions. • KeithVerheydensentinacorrectioninChapter3. • PeterWinstanleyletusknowaboutalongstandingerrorinourLatininChapter3. • ChrisWrobelmadecorrectionstothecodeinthechapteronfileI/Oandexceptions. • MosheZadkahasmadeinvaluablecontributionstothisproject.Inadditiontowritingthefirst draftofthechapteronDictionaries,heprovidedcontinualguidanceintheearlystagesofthe book. • ChristophZwerschkesentseveralcorrectionsandpedagogicsuggestions,andexplainedthe differencebetweengleichandselbe. • JamesMayersentusawholeslewofspellingandtypographicalerrors,includingtwointhe contributorlist. • HaydenMcAfeecaughtapotentiallyconfusinginconsistencybetweentwoexamples. • AngelArnalispartofaninternationalteamoftranslatorsworkingontheSpanishversionof thetext.HehasalsofoundseveralerrorsintheEnglishversion. • TauhidulHoqueandLexBerezhnycreatedtheillustrationsinChapter1andimprovedmany oftheotherillustrations. • Dr. MicheleAlzettacaughtanerrorinChapter8andsentsomeinterestingpedagogiccom- mentsandsuggestionsaboutFibonacciandOldMaid. • AndyMitchellcaughtatypoinChapter1andabrokenexampleinChapter2. • KalinHarveysuggestedaclarificationinChapter7andcaughtsometypos. • ChristopherP.SmithcaughtseveraltyposandhelpedusupdatethebookforPython2.2. • DavidHutchinscaughtatypointheForeword. • GregorLinglisteachingPythonatahighschoolinVienna,Austria. HeisworkingonaGer- mantranslationofthebook,andhecaughtacoupleofbaderrorsinChapter5. • JuliePeterscaughtatypointhePreface. • FlorinOprinasentinanimprovementinmakeTime,acorrectioninprintTime,andanicetypo. • D.J.WebresuggestedaclarificationinChapter3. • KenfoundafistfuloferrorsinChapters8,9and11. • IvoWevercaughtatypoinChapter5andsuggestedaclarificationinChapter3. • CurtisYankosuggestedaclarificationinChapter2. ix • BenLogansentinanumberoftyposandproblemswithtranslatingthebookintoHTML. • JasonArmstrongsawthemissingwordinChapter2. • LouisCordiernoticedaspotinChapter16wherethecodedidn’tmatchthetext. • BrianCainsuggestedseveralclarificationsinChapters2and3. • RobBlacksentinapasselofcorrections,includingsomechangesforPython2.2. • Jean-PhilippeReyatEcoleCentraleParissentanumberofpatches,includingsomeupdates forPython2.2andotherthoughtfulimprovements. • JasonMaderatGeorgeWashingtonUniversitymadeanumberofusefulsuggestionsandcor- rections. • JanGundtofte-Bruunremindedusthat“aerror”isanerror. • AbelDavidandAlexisDinnoremindedusthatthepluralof“matrix”is“matrices”,not“ma- trixes”.Thiserrorwasinthebookforyears,buttworeaderswiththesameinitialsreportedit onthesameday.Weird. • CharlesThayerencouragedustogetridofthesemi-colonswehadputattheendsofsome statementsandtocleanupouruseof“argument”and“parameter”. • RogerSperbergpointedoutatwistedpieceoflogicinChapter3. • SamBullpointedoutaconfusingparagraphinChapter2. • AndrewCheungpointedouttwoinstancesof“usebeforedef.” • C.CoreyCapelspottedthemissingwordintheThirdTheoremofDebuggingandatypoin Chapter4. • AlessandrahelpedclearupsomeTurtleconfusion. • WimChampagnefoundabrain-oinadictionaryexample. • DouglasWrightpointedoutaproblemwithfloordivisioninarc. • JaredSpindorfoundsomejetsamattheendofasentence. • LinPeihengsentanumberofveryhelpfulsuggestions. • RayHagtvedtsentintwoerrorsandanot-quite-error. • TorstenHübschpointedoutaninconsistencyinSwampy. • IngaPetuhhovcorrectedanexampleinChapter14. • ArneBabenhauserheidesentseveralhelpfulcorrections. • MarkE.Casidaisisgoodatspottingrepeatedwords. • ScottTylerfilledinathatwasmissing.Andthensentinaheapofcorrections. • GordonShephardsentinseveralcorrections,allinseparateemails. • AndrewTurnerspottedanerrorinChapter8. • AdamHobartfixedaproblemwithfloordivisioninarc. x Chapter0. Preface • DarylHammondandSarahZimmermanpointedoutthatIservedupmath.pitooearly. And Zimspottedatypo. • GeorgeSassfoundabuginaDebuggingsection. • BrianBinghamsuggestedExercise11.10. • LeahEngelbert-FentonpointedoutthatIusedtupleasavariablename,contrarytomyown advice.Andthenfoundabunchoftyposanda“usebeforedef.” • JoeFunkespottedatypo. • Chao-chaoChenfoundaninconsistencyintheFibonacciexample. • JeffPaineknowsthedifferencebetweenspaceandspam. • LubosPintessentinatypo. • GreggLindandAbigailHeithoffsuggestedExercise14.4. • MaxHailperinhassentinanumberofcorrectionsandsuggestions.Maxisoneoftheauthors oftheextraordinaryConcreteAbstractions,whichyoumightwanttoreadwhenyouaredone withthisbook. • ChotipatPornavalaifoundanerrorinanerrormessage. • StanislawAntolsentalistofveryhelpfulsuggestions. • EricPashmansentanumberofcorrectionsforChapters4–11. • MiguelAzevedofoundsometypos. • JianhuaLiusentinalonglistofcorrections. • NickKingfoundamissingword. • MartinZuthersentalonglistofsuggestions. • AdamZimmermanfoundaninconsistencyinmyinstanceofan“instance”andseveralother errors. • RatnakarTiwarisuggestedafootnoteexplainingdegeneratetriangles. • AnuragGoelsuggestedanothersolutionforis_abecedarianandsentsomeadditionalcorrec- tions.AndheknowshowtospellJaneAusten. • KelliKratzerspottedoneofthetypos. • MarkGriffithspointedoutaconfusingexampleinChapter3. • RoydanOngiefoundanerrorinmyNewton’smethod. • PatrykWolowiechelpedmewithaproblemintheHTMLversion. • MarkChonofskytoldmeaboutanewkeywordinPython3. • RussellColemanhelpedmewithmygeometry. • WeiHuangspottedseveraltypographicalerrors. • KarenBarberspottedthetheoldesttypointhebook.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.