ebook img

Think Python PDF

244 Pages·2017·0.78 MB·English
by  
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

Think Python How to Think Like a Computer Scientist 2ndEdition,Version2.2.21 Think Python How to Think Like a Computer Scientist 2ndEdition,Version2.2.21 Allen Downey Green Tea Press Needham,Massachusetts Copyright©2015AllenDowney. 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.thinkpython2.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 jargon and define each term at first use. • 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 Since then I’ve continued to develop the book, correcting errors, improving some of the examplesandaddingmaterial,especiallyexercises. Theresultisthisbook,nowwiththelessgrandiosetitleThinkPython. Someofthechanges are: • Iaddedasectionaboutdebuggingattheendofeachchapter. Thesesectionspresent general techniques for finding and avoiding bugs, and warnings about Python pit- falls. • Iaddedmoreexercises,rangingfromshorttestsofunderstandingtoafewsubstantial projects. Mostexercisesincludealinktomysolution. • Iaddedaseriesofcasestudies—longerexampleswithexercises,solutions,anddis- cussion. • Iexpandedthediscussionofprogramdevelopmentplansandbasicdesignpatterns. • Iaddedappendicesaboutdebuggingandanalysisofalgorithms. ThesecondeditionofThinkPythonhasthesenewfeatures: • ThebookandallsupportingcodehavebeenupdatedtoPython3. • I added a few sections, and more details on the web, to help beginners get started runningPythoninabrowser,soyoudon’thavetodealwithinstallingPythonuntil youwantto. • ForChapter4.1Iswitchedfrommyownturtlegraphicspackage,calledSwampy,toa morestandardPythonmodule,turtle,whichiseasiertoinstallandmorepowerful. • I added a new chapter called “The Goodies”, which introduces some additional Pythonfeaturesthatarenotstrictlynecessary,butsometimeshandy. Ihopeyouenjoyworkingwiththisbook,andthatithelpsyoulearntoprogramandthink likeacomputerscientist,atleastalittlebit. AllenB.Downey OlinCollege 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. vii ThankstotheeditorsatLuluwhoworkedonHowtoThinkLikeaComputerScientist. ThankstotheeditorsatO’ReillyMediawhoworkedonThinkPython. Thankstoallthestudentswhoworkedwithearlierversionsofthisbookandallthecon- tributors(listedbelow)whosentincorrectionsandsuggestions. 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. viii Chapter0. Preface • SimonDiconMontfordreportedamissingfunctiondefinitionandseveraltyposinChapter3. HealsofounderrorsintheincrementfunctioninChapter13. • JohnOuztscorrectedthedefinitionof“returnvalue"inChapter3. • KevinParkssentinvaluablecommentsandsuggestionsastohowtoimprovethedistribution ofthebook. • DavidPoolsentinatypointheglossaryofChapter1,aswellaskindwordsofencouragement. • MichaelSchmittsentinacorrectiontothechapteronfilesandexceptions. • 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. ix • JuliePeterscaughtatypointhePreface. • FlorinOprinasentinanimprovementinmakeTime,acorrectioninprintTime,andanicetypo. • D.J.WebresuggestedaclarificationinChapter3. • KenfoundafistfuloferrorsinChapters8,9and11. • IvoWevercaughtatypoinChapter5andsuggestedaclarificationinChapter3. • CurtisYankosuggestedaclarificationinChapter2. • 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. x Chapter0. Preface • MarkE.Casidaisisgoodatspottingrepeatedwords. • ScottTylerfilledinathatwasmissing.Andthensentinaheapofcorrections. • GordonShephardsentinseveralcorrections,allinseparateemails. • AndrewTurnerspottedanerrorinChapter8. • AdamHobartfixedaproblemwithfloordivisioninarc. • DarylHammondandSarahZimmermanpointedoutthatIservedupmath.pitooearly. And Zimspottedatypo. • GeorgeSassfoundabuginaDebuggingsection. • BrianBinghamsuggestedExercise11.5. • LeahEngelbert-FentonpointedoutthatIusedtupleasavariablename,contrarytomyown advice.Andthenfoundabunchoftyposanda“usebeforedef”. • JoeFunkespottedatypo. • Chao-chaoChenfoundaninconsistencyintheFibonacciexample. • JeffPaineknowsthedifferencebetweenspaceandspam. • LubosPintessentinatypo. • GreggLindandAbigailHeithoffsuggestedExercise14.3. • 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.

Description:
I added more exercises, ranging from short tests of understanding to a few I expanded the discussion of program development plans and basic design patterns Gregg Lind and Abigail Heithoff suggested Exercise 14.3. Here the tuples are shown using Python syntax as a graphical shorthand.
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.