Think Python
Think Python
Think Python
ThinkPython/Printversion Preface
Chapter0:Preface
Thestrangehistoryofthisbook
(ThissectionwaswrittenbyAllenB.Downey[1]) InJanuary1999,IwaspreparingtoteachanintroductoryprogrammingclassinJava.IhadtaughtitthreetimesandIwasgettingfrustrated.Thefailurerate intheclasswastoohighand,evenforstudentswhosucceeded,theoveralllevelofachievementwastoolow. OneoftheproblemsIsawwasthebooks.Theyweretoobig,withtoomuchunnecessarydetailaboutJava,andnotenoughhighlevelguidanceabouthowto program.Andtheyallsufferedfromthe"trapdooreffect":theywouldstartouteasy,proceedgradually,andthensomewherearoundChapter5thebottom wouldfallout.Thestudentswouldgettoomuchnewmaterial,toofast,andIwouldspendtherestofthesemesterpickingupthepieces. Twoweeksbeforethefirstdayofclass,Idecidedtowritemyownbook. Mygoalswere: Keepitshort.Itisbetterforstudentstoread10pagesthanread50pages. Becarefulwithvocabulary.Itriedtominimizethejargonanddefineeachtermatfirstuse. Buildgradually.Toavoidtrapdoors,Itookthemostdifficulttopicsandsplitthemintoaseriesofsmallsteps. Focusonprogramming,nottheprogramminglanguage.IincludedtheminimumusefulsubsetofJavaandleftouttherest. Ineededatitle,soonawhimIchose HowtoThinkLikeaComputerScientist . Myfirstversionwasrough,butitworked.Studentsdidthereading,andtheyunderstoodenoughthatIcouldspendclasstimeonthehardtopics,the interestingtopicsand(mostimportant)lettingthestudentspractice. IreleasedthebookundertheGNUFreeDocumentationLicense,whichallowsuserstocopy,modify,anddistributethebook. Whathappenednextisthecoolpart.JeffElkner,ahighschoolteacherinVirginia,adoptedmybookandtranslateditintoPython.Hesentmeacopyofhis translation,andIhadtheunusualexperienceoflearningPythonbyreadingmyownbook. JeffandIrevisedthebook,incorporatedacasestudybyChrisMeyers,andin2001wereleased HowtoThinkLikeaComputerScientist:Learningwith Python,alsoundertheGNUFreeDocumentationLicense.AsGreenTeaPress,IpublishedthebookandstartedsellinghardcopiesthroughAmazon.comand collegebookstores.OtherbooksfromGreenTeaPressareavailableatgreenteapress.com(http://www.greenteapress.com/). In2003,IstartedteachingatOlinCollegeandIgottoteachPythonforthefirsttime.ThecontrastwithJavawasstriking.Studentsstruggledless,learned more,workedonmoreinterestingprojects,andgenerallyhadalotmorefun. OverthelastfiveyearsIhavecontinuedtodevelopthebook,correctingerrors,improvingsomeoftheexamplesandaddingmaterial,especiallyexercises.In
en.wikibooks.org/wiki/Think_Python/Print_version
1/282
10/24/13
OverthelastfiveyearsIhavecontinuedtodevelopthebook,correctingerrors,improvingsomeoftheexamplesandaddingmaterial,especiallyexercises.In 2008Istartedworkonamajorrevisionatthesametime,IwascontactedbyaneditoratCambridgeUniversityPresswhowasinterestedinpublishingthe nextedition.Goodtiming! Theresultisthisbook,nowwiththelessgrandiosetitle ThinkPython.Someofthechangesare: Iaddedasectionaboutdebuggingattheendofeachchapter.Thesesectionspresentgeneraltechniquesforfindingandavoidingbugs,andwarnings aboutPythonpitfalls. Iremovedthematerialinthelastfewchaptersabouttheimplementationoflistsandtrees.Istilllovethosetopics,butIthoughttheywereincongruent withtherestofthebook. Iaddedmoreexercises,rangingfromshorttestsofunderstandingtoafewsubstantialprojects. Iaddedaseriesofcasestudieslongerexampleswithexercises,solutions,anddiscussion.SomeofthemarebasedonSwampy,asuiteofPython programsIwroteforuseinmyclasses.Swampy,codeexamples,andsomesolutionsareavailablefromthinkpython.com (http://www.thinkpython.com). Iexpandedthediscussionofprogrammingdevelopmentplansandbasicdesignpatterns. TheuseofPythonismoreidiomatic.Thebookisstillaboutprogramming,notPython,butnowIthinkthebookgetsmoreleveragefromthelanguage. Ihopeyouenjoyworkingwiththisbook,andthatithelpsyoulearntoprogramandthink,atleastalittlebit,likeacomputerscientist. AllenB.Downey NeedhamMA AllenDowneyisanAssociateProfessorofComputerScienceattheFranklinW.OlinCollegeofEngineering.
Acknowledgements
Firstandmostimportantly,IthankJeffElkner,whotranslatedmyJavabookintoPython,whichgotthisprojectstartedandintroducedmetowhathasturned outtobemyfavoritelanguage. IalsothankChrisMeyers,whocontributedseveralsectionsto HowtoThinkLikeaComputerScientist . AndIthanktheFreeSoftwareFoundationfordevelopingtheGNUFreeDocumentationLicense,whichhelpedmakemycollaborationwithJeffandChris possible. IalsothanktheeditorsatLuluwhoworkedon HowtoThinkLikeaComputerScientist . Ithankallthestudentswhoworkedwithearlierversionsofthisbookandallthecontributors(listedbelow)whosentincorrectionsandsuggestions. AndIthankmywife,Lisa,forherworkonthisbook,andGreenTeaPress,andeverythingelse,too.
ContributorList
en.wikibooks.org/wiki/Think_Python/Print_version
Morethan100sharpeyedandthoughtfulreadershavesentinsuggestionsandcorrectionsoverthepastfewyears.Theircontributions,andenthusiasmfor
2/282
10/24/13
Morethan100sharpeyedandthoughtfulreadershavesentinsuggestionsandcorrectionsoverthepastfewyears.Theircontributions,andenthusiasmfor thisproject,havebeenahugehelp. Ifyouhaveasuggestionorcorrection,pleasesendemailto f e e d b a c k @ t h i n k p y t h o n . c o m .IfImakeachangebasedonyourfeedback,Iwilladdyoutothecontributor list(unlessyouasktobeomitted). Ifyouincludeatleastpartofthesentencetheerrorappearsin,thatmakesiteasyformetosearch.Pageandsectionnumbersarefine,too,butnotquiteas easytoworkwith.Thanks! LloydHughAllensentinacorrectiontoSection8.4. YvonBouliannesentinacorrectionofasemanticerrorinChapter5. FredBremmersubmittedacorrectioninSection2.1. JonahCohenwrotethePerlscriptstoconverttheLaTeXsourceforthisbookintobeautifulHTML. MichaelConlonsentinagrammarcorrectioninChapter2andanimprovementinstyleinChapter1,andheinitiateddiscussiononthetechnical aspectsofinterpreters. BenoitGirardsentinacorrectiontoahumorousmistakeinSection5.6. CourtneyGleasonandKatherineSmithwrote h o r s e b e t . p y ,whichwasusedasacasestudyinanearlierversionofthebook.Theirprogramcannowbe foundonthewebsite. LeeHarrsubmittedmorecorrectionsthanwehaveroomtolisthere,andindeedheshouldbelistedasoneoftheprincipaleditorsofthetext. JamesKaylinisastudentusingthetext.Hehassubmittednumerouscorrections. DavidKershawfixedthebroken c a t T w i c e functioninSection3.10. EddieLamhassentinnumerouscorrectionstoChapters1,2,and3.HealsofixedtheMakefilesothatitcreatesanindexthefirsttimeitisrunand helpedussetupaversioningscheme. ManYongLeesentinacorrectiontotheexamplecodeinSection2.4. DavidMayopointedoutthattheword"unconsciously"inChapter1neededtobechangedto"subconsciously". ChrisMcAloonsentinseveralcorrectionstoSections3.9and3.10. MatthewJ.Moelterhasbeenalongtimecontributorwhosentinnumerouscorrectionsandsuggestionstothebook. SimonDiconMontfordreportedamissingfunctiondefinitionandseveraltyposinChapter3.Healsofounderrorsinthe i n c r e m e n t functioninChapter13. JohnOuztscorrectedthedefinitionof"returnvalue"inChapter3. KevinParkssentinvaluablecommentsandsuggestionsastohowtoimprovethedistributionofthebook. DavidPoolsentinatypointheglossaryofChapter1,aswellaskindwordsofencouragement. MichaelSchmittsentinacorrectiontothechapteronfilesandexceptions. RobinShawpointedoutanerrorinSection13.1,wherethe p r i n t T i m e functionwasusedinanexamplewithoutbeingdefined. PaulSleighfoundanerrorinChapter7andabuginJonahCohensPerlscriptthatgeneratesHTMLfromLaTeX. CraigT.SnydalistestingthetextinacourseatDrewUniversity.Hehascontributedseveralvaluablesuggestionsandcorrections.
en.wikibooks.org/wiki/Think_Python/Print_version 3/282
10/24/13
IanThomasandhisstudentsareusingthetextinaprogrammingcourse.Theyarethefirstonestotestthechaptersinthelatterhalfofthebook,and theyhavemadenumerouscorrectionsandsuggestions. KeithVerheydensentinacorrectioninChapter3. PeterWinstanleyletusknowaboutalongstandingerrorinourLatininChapter3. ChrisWrobelmadecorrectionstothecodeinthechapteronfileI/Oandexceptions. MosheZadkahasmadeinvaluablecontributionstothisproject.InadditiontowritingthefirstdraftofthechapteronDictionaries,he providedcontinualguidanceintheearlystagesofthebook. ChristophZwerschkesentseveralcorrectionsandpedagogicsuggestions,andexplainedthedifferencebetween gleichand selbe. JamesMayersentusawholeslewofspellingandtypographicalerrors,includingtwointhecontributorlist. HaydenMcAfeecaughtapotentiallyconfusinginconsistencybetweentwoexamples. AngelArnalispartofaninternationalteamoftranslatorsworkingontheSpanishversionofthetext.HehasalsofoundseveralerrorsintheEnglish version. TauhidulHoqueandLexBerezhnycreatedtheillustrationsinChapter1andimprovedmanyoftheotherillustrations. Dr.MicheleAlzettacaughtanerrorinChapter8andsentsomeinterestingpedagogiccommentsandsuggestionsaboutFibonacciandOldMaid. AndyMitchellcaughtatypoinChapter1andabrokenexampleinChapter2. KalinHarveysuggestedaclarificationinChapter7andcaughtsometypos. ChristopherP.SmithcaughtseveraltyposandishelpinguspreparetoupdatethebookforPython2.2. DavidHutchinscaughtatypointheForeword. GregorLinglisteachingPythonatahighschoolinVienna,Austria.HeisworkingonaGermantranslationofthebook,andhecaughtacoupleofbad errorsinChapter5. JuliePeterscaughtatypointhePreface. FlorinOprinasentinanimprovementin m a k e T i m e ,acorrectionin p r i n t T i m e ,andanicetypo. D.J.WebresuggestedaclarificationinChapter3. KenfoundafistfuloferrorsinChapters8,9and11. IvoWevercaughtatypoinChapter5andsuggestedaclarificationinChapter3. CurtisYankosuggestedaclarificationinChapter2. BenLogansentinanumberoftyposandproblemswithtranslatingthebookintoHTML. JasonArmstrongsawthemissingwordinChapter2. LouisCordiernoticedaspotinChapter16wherethecodedidn'tmatchthetext. BrianCainsuggestedseveralclarificationsinChapters2and3. RobBlacksentinapasselofcorrections,includingsomechangesforPython2.2. JeanPhilippeReyatEcoleCentraleParissentanumberofpatches,includingsomeupdatesforPython2.2andotherthoughtfulimprovements. JasonMaderatGeorgeWashingtonUniversitymadeanumberofusefulsuggestionsandcorrections. JanGundtofteBruunremindedusthataerrorisanerror.
en.wikibooks.org/wiki/Think_Python/Print_version 4/282
10/24/13
AbelDavidandAlexisDinnoremindedusthatthepluralofmatrixismatrices,notmatrixes.Thiserrorwasinthebookforyears,buttworeaders withthesameinitialsreporteditonthesameday.Weird. CharlesThayerencouragedustogetridofthesemicolonswehadputattheendsofsomestatementsandtocleanupouruseofargumentand parameter. RogerSperbergpointedoutatwistedpieceoflogicinChapter3. SamBullpointedoutaconfusingparagraphinChapter2. AndrewCheungpointedouttwoinstancesofusebeforedef. C.CoreyCapelspottedthemissingwordintheThirdTheoremofDebuggingandatypoinChapter4. AlessandrahelpedclearupsomeTurtleconfusion. WimChampagnefoundabrainoinadictionaryexample. DouglasWrightpointedoutaproblemwithfloordivisionin a r c . JaredSpindorfoundsomejetsamattheendofasentence. LinPeihengsentanumberofveryhelpfulsuggestions. RayHagtvedtsentintwoerrorsandanotquiteerror. TorstenHbschpointedoutaninconsistencyinSwampy. IngaPetuhhovcorrectedanexampleinChapter14. ArneBabenhauserheidesentseveralhelpfulcorrections. MarkE.Casidaisisgoodatspottingrepeatedwords. ScottTylerfilledinathatwasmissing.Andthensentinaheapofcorrections. GordonShephardsentinseveralcorrections,allinseparateemails. AndrewTurner s p o t tedanerrorinChapter8. AdamHobartfixedaproblemwithfloordivisionin a r c . DarylHammondandSarahZimmermanpointedoutthatIservedup m a t h . p i tooearly.AndZimspottedatypo. GeorgeSassfoundabuginaDebuggingsection. BrianBinghamsuggestedExercise11.9. LeahEngelbertFentonpointedoutthatIused t u p l e asavariablename,contrarytomyownadvice.Andthenfoundabunchoftyposandausebefore def. JoeFunkespottedatypo. ChaochaoChenfoundaninconsistencyintheFibonacciexample. JeffPaineknowsthedifferencebetweenspaceandspam. LubosPintessentinatypo. GreggLindandAbigailHeithoffsuggestedExercise14.6. MaxHailperinpointedoutachangecominginPython3.0.Maxisoneoftheauthorsoftheextraordinary ConcreteAbstractions,whichyoumightwant toreadwhenyouaredonewiththisbook. ChotipatPornavalaifoundanerrorinanerrormessage.
en.wikibooks.org/wiki/Think_Python/Print_version 5/282
10/24/13
StanislawAntolsentalistofveryhelpfulsuggestions. EricPashmansentanumberofcorrectionsforChapters411. MiguelAzevedofoundsometypos. JianhuaLiusentinalonglistofcorrections. NickKingfoundamissingword. MartinZuthersentalonglistofsuggestions. AdamZimmermanfoundaninconsistencyinmyinstanceofaninstanceandseveralothererrors. RatnakarTiwarisuggestedafootnoteexplainingdegeneratetriangles. AnuragGoelsuggestedanothersolutionfor i s _ a b e c e d a r i a n andsentsomeadditionalcorrections.AndheknowshowtospellJaneAusten. KelliKratzerspottedoneoftheytypos. MarkGriffithspointedoutaconfusingexampleinChapter3. RoydanOngiefoundanerrorinmyNewtonsmethod.
Thefurtherstrangeadventuresofthisbook
InSeptemberof2008,WhiteknightconvertedtheHTMLversionof"ThinkPython"atGreenTeaPress[2]toaWikitextversionatWikibooks[3].Nowanyone canimprovethetext. 1. "Thestrangehistoryofthisbook"(http://www.greenteapress.com/thinkpython/html/book001.html)byAllenB.Downey 2. "ThinkPython"atGreenTeaPress(http://thinkpython.com/) 3. Wikibooks:ThinkPython(http://en.wikibooks.org/wiki/Think_Python)
Thewayoftheprogram
Thegoalofthisbookistoteachyoutothinklikeacomputerscientist.Thiswayofthinkingcombinessomeofthebestfeaturesofmathematics,engineering, andnaturalscience.Likemathematicians,computerscientistsuseformallanguagestodenoteideas(specificallycomputations).Likeengineers,theydesign things,assemblingcomponentsintosystemsandevaluatingtradeoffsamongalternatives.Likescientists,theyobservethebehaviorofcomplexsystems,form hypotheses,andtestpredictions. Thesinglemostimportantskillforacomputerscientistis problemsolving.Problemsolvingmeanstheabilitytoformulateproblems,thinkcreativelyabout solutions,andexpressasolutionclearlyandaccurately.Asitturnsout,theprocessoflearningtoprogramisanexcellentopportunitytopracticeproblem solvingskills.Thatswhythischapteriscalled,Thewayoftheprogram. Ononelevel,youwillbelearningtoprogram,ausefulskillbyitself.Onanotherlevel,youwilluseprogrammingasameanstoanend.Aswegoalong,that endwillbecomeclearer.
ThePythonprogramminglanguage
TheprogramminglanguageyouwilllearnisPython.Pythonisanexampleofa highlevellanguageotherhighlevellanguagesyoumighthaveheardofare C,C++,Perl,andJava.
en.wikibooks.org/wiki/Think_Python/Print_version 6/282
10/24/13
Therearealso lowlevellanguages,sometimesreferredtoasmachinelanguagesorassemblylanguages.Looselyspeaking,computerscanonlyexecute programswritteninlowlevellanguages.Soprogramswritteninahighlevellanguagehavetobeprocessedbeforetheycanrun.Thisextraprocessingtakes sometime,whichisasmalldisadvantageofhighlevellanguages. Theadvantagesareenormous.First,itismucheasiertoprograminahighlevellanguage.Programswritteninahighlevellanguagetakelesstimetowrite, theyareshorterandeasiertoread,andtheyaremorelikelytobecorrect.Second,highlevellanguagesare portable,meaningthattheycanrunondifferent kindsofcomputerswithfewornomodifications.Lowlevelprogramscanrunononlyonekindofcomputerandhavetoberewrittentorunonanother. Duetotheseadvantages,almostallprogramsarewritteninhighlevellanguages.Lowlevellanguagesareusedonlyforafewspecializedapplications. Twokindsofprogramsprocesshighlevellanguagesintolowlevellanguages: interpretersand compilers.Aninterpreterreadsahighlevelprogramand executesit,meaningthatitdoeswhattheprogramsays.Itprocessestheprogramalittleatatime,alternatelyreadinglinesandperformingcomputations.
Thechevron, > > > ,isthe prompttheinterpreterusestoindicatethatitisready.Ifyoutype 1+1 ,theinterpreterreplies 2 . Alternatively,youcanstorecodeinafileandusetheinterpretertoexecutethecontentsofthefile,whichiscalleda script.Byconvention,Pythonscripts havenamesthatendwith . p y .
en.wikibooks.org/wiki/Think_Python/Print_version 7/282
10/24/13
Whatisaprogram?
A programisasequenceofinstructionsthatspecifieshowtoperformacomputation.Thecomputationmightbesomethingmathematical,suchassolvinga systemofequationsorfindingtherootsofapolynomial,butitcanalsobeasymboliccomputation,suchassearchingandreplacingtextinadocumentor (strangelyenough)compilingaprogram. Thedetailslookdifferentindifferentlanguages,butafewbasicinstructionsappearinjustabouteverylanguage: input: Getdatafromthekeyboard,afile,orsomeotherdevice. output: Displaydataonthescreenorsenddatatoafileorotherdevice. math: Performbasicmathematicaloperationslikeadditionandmultiplication. conditionalexecution: Checkforcertainconditionsandexecutetheappropriatesequenceofstatements. repetition: Performsomeactionrepeatedly,usuallywithsomevariation. Believeitornot,thatsprettymuchallthereistoit.Everyprogramyouveeverused,nomatterhowcomplicated,ismadeupofinstructionsthatlookpretty muchlikethese.Soyoucanthinkofprogrammingastheprocessofbreakingalarge,complextaskintosmallerandsmallersubtasksuntilthesubtasksare simpleenoughtobeperformedwithoneofthesebasicinstructions. Thatmaybealittlevague,butwewillcomebacktothistopicwhenwetalkabout algorithms.
Whatisdebugging?
Programmingiserrorprone.Forwhimsicalreasons,programmingerrorsarecalled bugsandtheprocessoftrackingthemdowniscalled debugging. Threekindsoferrorscanoccurinaprogram:syntaxerrors,runtimeerrors,andsemanticerrors.Itisusefultodistinguishbetweentheminordertotrackthem downmorequickly. Syntaxerrors Pythoncanonlyexecuteaprogramifthesyntaxiscorrectotherwise,theinterpreterdisplaysanerrormessage. Syntaxreferstothestructureofaprogram andtherulesaboutthatstructure.Forexample,parentheseshavetocomeinmatchingpairs,so ( 1+2 ) islegal,but 8 ) isa syntaxerror.
en.wikibooks.org/wiki/Think_Python/Print_version 8/282
10/24/13
InEnglishreaderscantoleratemostsyntaxerrors,whichiswhywecanreadthepoetryofE.E.Cummingswithoutspewingerrormessages.Pythonisnotso forgiving.Ifthereisasinglesyntaxerroranywhereinyourprogram,Pythonwilldisplayanerrormessageandquit,andyouwillnotbeabletorunyour program.Duringthefirstfewweeksofyourprogrammingcareer,youwillprobablyspendalotoftimetrackingdownsyntaxerrors.Asyougainexperience,you willmakefewererrorsandfindthemfaster. Runtimeerrors Thesecondtypeoferrorisaruntimeerror,socalledbecausetheerrordoesnotappearuntilaftertheprogramhasstartedrunning.Theseerrorsarealso called exceptionsbecausetheyusuallyindicatethatsomethingexceptional(andbad)hashappened. Runtimeerrorsarerareinthesimpleprogramsyouwillseeinthefirstfewchapters,soitmightbeawhilebeforeyouencounterone. Semanticerrors Thethirdtypeoferroristhe semanticerror.Ifthereisasemanticerrorinyourprogram,itwillrunsuccessfullyinthesensethatthecomputerwillnot generateanyerrormessages,butitwillnotdotherightthing.Itwilldosomethingelse.Specifically,itwilldowhatyoutoldittodo. Theproblemisthattheprogramyouwroteisnottheprogramyouwantedtowrite.Themeaningoftheprogram(itssemantics)iswrong.Identifyingsemantic errorscanbetrickybecauseitrequiresyoutoworkbackwardbylookingattheoutputoftheprogramandtryingtofigureoutwhatitisdoing. Experimentaldebugging Oneofthemostimportantskillsyouwillacquireisdebugging.Althoughitcanbefrustrating,debuggingisoneofthemostintellectuallyrich,challenging,and interestingpartsofprogramming. Insomeways,debuggingislikedetectivework.Youareconfrontedwithclues,andyouhavetoinfertheprocessesandeventsthatledtotheresultsyousee. Debuggingisalsolikeanexperimentalscience.Onceyouhaveanideaaboutwhatisgoingwrong,youmodifyyourprogramandtryagain.Ifyourhypothesis wascorrect,thenyoucanpredicttheresultofthemodification,andyoutakeastepclosertoaworkingprogram.Ifyourhypothesiswaswrong,youhaveto comeupwithanewone.AsSherlockHolmespointedout,Whenyouhaveeliminatedtheimpossible,whateverremains,howeverimprobable,mustbethe truth.(A.ConanDoyle, TheSignofFour) Forsomepeople,programminganddebuggingarethesamething.Thatis,programmingistheprocessofgraduallydebuggingaprogramuntilitdoeswhat youwant.Theideaisthatyoushouldstartwithaprogramthatdoes somethingandmakesmallmodifications,debuggingthemasyougo,sothatyoualways haveaworkingprogram. Forexample,Linuxisanoperatingsystemthatcontainsthousandsoflinesofcode,butitstartedoutasasimpleprogramLinusTorvaldsusedtoexplorethe Intel80386chip.AccordingtoLarryGreenfield,OneofLinussearlierprojectswasaprogramthatwouldswitchbetweenprintingAAAAandBBBB.Thislater evolvedtoLinux.(TheLinuxUsersGuideBetaVersion1). Laterchapterswillmakemoresuggestionsaboutdebuggingandotherprogrammingpractices.
Formalandnaturallanguages
en.wikibooks.org/wiki/Think_Python/Print_version 9/282
10/24/13
Naturallanguagesarethelanguagespeoplespeak,suchasEnglish,Spanish,andFrench.Theywerenotdesignedbypeople(althoughpeopletrytoimpose someorderonthem)theyevolvednaturally. Formallanguagesarelanguagesthataredesignedbypeopleforspecificapplications.Forexample,thenotationthatmathematiciansuseisaformal languagethatisparticularlygoodatdenotingrelationshipsamongnumbersandsymbols.Chemistsuseaformallanguagetorepresentthechemicalstructure ofmolecules.Andmostimportantly: Programminglanguagesareformallanguagesthathavebeendesignedtoexpresscomputations. Formallanguagestendtohavestrictrulesaboutsyntax.Forexample,3+3=6isasyntacticallycorrectmathematicalstatement,but3+=3$6isnot. H2O isasyntacticallycorrectchemicalformula,but 2Zzisnot. Syntaxrulescomeintwoflavors,pertainingto tokensandstructure.Tokensarethebasicelementsofthelanguage,suchaswords,numbers,andchemical elements.Oneoftheproblemswith3+=3$6isthat $ isnotalegaltokeninmathematics(atleastasfarasIknow).Similarly, 2Zzisnotlegalbecause thereisnoelementwiththeabbreviation Zz. Thesecondtypeofsyntaxerrorpertainstothestructureofastatementthatis,thewaythetokensarearranged.Thestatement3+=3$6isillegalbecause eventhough+and=arelegaltokens,youcanthaveonerightaftertheother.Similarly,inachemicalformulathesubscriptcomesaftertheelementname, notbefore. Exercise1 WriteawellstructuredEnglishsentencewithinvalidtokensinit.Thenwriteanothersentencewithallvalidtokensbutwithinvalidstructure. WhenyoureadasentenceinEnglishorastatementinaformallanguage,youhavetofigureoutwhatthestructureofthesentenceis(althoughinanatural languageyoudothissubconsciously).Thisprocessiscalled parsing. Forexample,whenyouhearthesentence,Thepennydropped,youunderstandthatthepennyisthesubjectanddroppedisthepredicate.Onceyouhave parsedasentence,youcanfigureoutwhatitmeans,orthesemanticsofthesentence.Assumingthatyouknowwhatapennyisandwhatitmeanstodrop, youwillunderstandthegeneralimplicationofthissentence. Althoughformalandnaturallanguageshavemanyfeaturesincommontokens,structure,syntax,andsemanticstherearesomedifferences: ambiguity: Naturallanguagesarefullofambiguity,whichpeopledealwithbyusingcontextualcluesandotherinformation.Formallanguagesaredesignedtobe nearlyorcompletelyunambiguous,whichmeansthatanystatementhasexactlyonemeaning,regardlessofcontext. redundancy: Inordertomakeupforambiguityandreducemisunderstandings,naturallanguagesemploylotsofredundancy.Asaresult,theyareoftenverbose. Formallanguagesarelessredundantandmoreconcise. literalness: Naturallanguagesarefullofidiomandmetaphor.IfIsay,Thepennydropped,thereisprobablynopennyandnothingdropping[1].Formallanguages meanexactlywhattheysay.
en.wikibooks.org/wiki/Think_Python/Print_version 10/282
10/24/13
Peoplewhogrowupspeakinganaturallanguageeveryoneoftenhaveahardtimeadjustingtoformallanguages.Insomeways,thedifferencebetween formalandnaturallanguageislikethedifferencebetweenpoetryandprose,butmoreso: Poetry: Wordsareusedfortheirsoundsaswellasfortheirmeaning,andthewholepoemtogethercreatesaneffectoremotionalresponse.Ambiguityisnot onlycommonbutoftendeliberate. Prose: Theliteralmeaningofwordsismoreimportant,andthestructurecontributesmoremeaning.Proseismoreamenabletoanalysisthanpoetrybutstill oftenambiguous. Programs: Themeaningofacomputerprogramisunambiguousandliteral,andcanbeunderstoodentirelybyanalysisofthetokensandstructure. Herearesomesuggestionsforreadingprograms(andotherformallanguages).First,rememberthatformallanguagesaremuchmoredensethannatural languages,soittakeslongertoreadthem.Also,thestructureisveryimportant,soitisusuallynotagoodideatoreadfromtoptobottom,lefttoright. Instead,learntoparsetheprograminyourhead,identifyingthetokensandinterpretingthestructure.Finally,thedetailsmatter.Smallerrorsinspellingand punctuation,whichyoucangetawaywithinnaturallanguages,canmakeabigdifferenceinaformallanguage.
Thefirstprogram
Traditionally,thefirstprogramyouwriteinanewlanguageiscalledHello,World!becauseallitdoesisdisplaythewords,Hello,World!InPython,itlooks likethis:
p r i n t' H e l l o ,W o r l d ! '
Debugging
Itisagoodideatoreadthisbookinfrontofacomputersoyoucantryouttheexamplesasyougo.Youcanrunmostoftheexamplesininteractivemode, butifyouputthecodeintoascript,itiseasiertotryoutvariations.
en.wikibooks.org/wiki/Think_Python/Print_version
Wheneveryouareexperimentingwithanewfeature,youshouldtrytomakemistakes.Forexample,intheHello,world!program,whathappensifyouleave
11/282
10/24/13
Wheneveryouareexperimentingwithanewfeature,youshouldtrytomakemistakes.Forexample,intheHello,world!program,whathappensifyouleave outoneofthequotationmarks?Whatifyouleaveoutboth?Whatifyouspell p r i n t wrong? Thiskindofexperimenthelpsyourememberwhatyoureaditalsohelpswithdebugging,becauseyougettoknowwhattheerrormessagesmean.Itisbetter tomakemistakesnowandonpurposethanlaterandaccidentally. Programming,andespeciallydebugging,sometimesbringsoutstrongemotions.Ifyouarestrugglingwithadifficultbug,youmightfeelangry,despondentor embarrassed. Thereisevidencethatpeoplenaturallyrespondtocomputersasiftheywerepeople[3].Whentheyworkwell,wethinkofthemasteammates,andwhenthey areobstinateorrude,werespondtothemthesamewaywerespondtorude,obstinatepeople. Preparingforthesereactionsmighthelpyoudealwiththem.Oneapproachistothinkofthecomputerasanemployeewithcertainstrengths,likespeedand precision,andparticularweaknesses,likelackofempathyandinabilitytograspthebigpicture. Yourjobistobeagoodmanager:findwaystotakeadvantageofthestrengthsandmitigatetheweaknesses.Andfindwaystouseyouremotionstoengage withtheproblem,withoutlettingyourreactionsinterferewithyourabilitytoworkeffectively. Learningtodebugcanbefrustrating,butitisavaluableskillthatisusefulformanyactivitiesbeyondprogramming.Attheendofeachchapterthereisa debuggingsection,likethisone,withmythoughtsaboutdebugging.Ihopetheyhelp!
Glossary
problemsolving: Theprocessofformulatingaproblem,findingasolution,andexpressingthesolution. highlevellanguage: AprogramminglanguagelikePythonthatisdesignedtobeeasyforhumanstoreadandwrite. lowlevellanguage: Aprogramminglanguagethatisdesignedtobeeasyforacomputertoexecutealsocalledmachinelanguageorassemblylanguage. portability: Apropertyofaprogramthatcanrunonmorethanonekindofcomputer. interpret: Toexecuteaprograminahighlevellanguagebytranslatingitonelineatatime. compile: Totranslateaprogramwritteninahighlevellanguageintoalowlevellanguageallatonce,inpreparationforlaterexecution. sourcecode: Aprograminahighlevellanguagebeforebeingcompiled. objectcode: Theoutputofthecompilerafterittranslatestheprogram. executable: Anothernameforobjectcodethatisreadytobeexecuted.
en.wikibooks.org/wiki/Think_Python/Print_version 12/282
10/24/13
prompt: Charactersdisplayedbytheinterpretertoindicatethatitisreadytotakeinputfromtheuser. script: Aprogramstoredinafile(usuallyonethatwillbeinterpreted). interactivemode: AwayofusingthePythoninterpreterbytypingcommandsandexpressionsattheprompt. scriptmode: AwayofusingthePythoninterpretertoreadandexecutestatementsinascript. program: Asetofinstructionsthatspecifiesacomputation. algorithm: Ageneralprocessforsolvingacategoryofproblems. bug: Anerrorinaprogram. debugging: Theprocessoffindingandremovinganyofthethreekindsofprogrammingerrors. syntax: Thestructureofaprogram. syntaxerror: Anerrorinaprogramthatmakesitimpossibletoparse(andthereforeimpossibletointerpret). exception: Anerrorthatisdetectedwhiletheprogramisrunning. semantics: Themeaningofaprogram. semanticerror: Anerrorinaprogramthatmakesitdosomethingotherthanwhattheprogrammerintended. naturallanguage: Anyoneofthelanguagesthatpeoplespeakthatevolvednaturally. formallanguage: Anyoneofthelanguagesthatpeoplehavedesignedforspecificpurposes,suchasrepresentingmathematicalideasorcomputerprogramsall programminglanguagesareformallanguages. token: Oneofthebasicelementsofthesyntacticstructureofaprogram,analogoustoawordinanaturallanguage. parse: Toexamineaprogramandanalyzethesyntacticstructure.
en.wikibooks.org/wiki/Think_Python/Print_version 13/282
10/24/13
printstatement: AninstructionthatcausesthePythoninterpretertodisplayavalueonthescreen.
Exercises
Exercise2 UseawebbrowsertogotothePythonwebsite,http://python.org/.ThispagecontainsinformationaboutPythonandlinkstoPythonrelatedpages,andit givesyoutheabilitytosearchthePythondocumentation.Forexample,ifyouenter p r i n t inthesearchwindow,thefirstlinkthatappearsisthedocumentation ofthe p r i n t statement.Atthispoint,notallofitwillmakesensetoyou,butitisgoodtoknowwhereitis. Exercise3 StartthePythoninterpreterandtype'h e l p ( ) 'tostarttheonlinehelputility.Oryoucantype h e l p ( ' p r i n t ' ) togetinformationaboutthe'p r i n t 'statement. Ifthis exampledoesntwork,youmayneedtoinstalladditionalPythondocumentationorsetanenvironmentvariablethedetailsdependonyouroperatingsystem andversionofPython. Exercise4 StartthePythoninterpreteranduseitasacalculator.Pythonssyntaxformathoperationsisalmostthesameasstandardmathematicalnotation.For example,thesymbols'+ ',''and'/ 'denoteaddition,subtractionanddivision,asyouwouldexpect.Thesymbolformultiplicationis'* '. Ifyouruna10kilometer racein43minutes30seconds,whatisyouraveragetimepermile?Whatisyouraveragespeedinmilesperhour?(Hint:thereare1.61kilometersinamile).
References
1. Thisidiommeansthatsomeonerealizedsomethingafteraperiodofconfusion. 2. InPython3.0, p r i n t isafunction,notastatement,sothesyntaxis p r i n t ( H e l l o ,W o r l d ! ) .Wewillgettofunctionssoon! 3. SeeReevesandNass, TheMediaEquation:HowPeopleTreatComputers,Television,andNewMediaLikeRealPeopleandPlaces.
Variables,expressionsandstatements
Valuesandtypes
A valueisoneofthebasicthingsaprogramworkswith,likealetteroranumber.Thevalueswehaveseensofarare 1 , 2 ,and ' H e l l o ,W o r l d ! ' . Thesevaluesbelongtodifferent types: 2 isaninteger,and ' H e l l o ,W o r l d ! ' isa string,socalledbecauseitcontainsastringofletters.You(andthe interpreter)canidentifystringsbecausetheyareenclosedinquotationmarks. Theprintstatementalsoworksforintegers.
en.wikibooks.org/wiki/Think_Python/Print_version
14/282
10/24/13
Ifyouarenotsurewhattypeavaluehas,theinterpretercantellyou.
> > >t y p e ( ' H e l l o ,W o r l d ! ' ) < t y p e' s t r ' > > > >t y p e ( 1 7 ) < t y p e' i n t ' >
Variables
Oneofthemostpowerfulfeaturesofaprogramminglanguageistheabilitytomanipulate variables.Avariableisanamethatreferstoavalue. An assignmentstatementcreatesnewvariablesandgivesthemvalues:
en.wikibooks.org/wiki/Think_Python/Print_version
15/282
10/24/13
> > >m e s s a g e=' A n dn o wf o rs o m e t h i n gc o m p l e t e l yd i f f e r e n t ' > > >n=1 7 > > >p i=3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 1
Todisplaythevalueofavariable,youcanuseaprintstatement:
> > >p r i n tn 1 7 > > >p r i n tp i 3 . 1 4 1 5 9 2 6 5 3 5 9
Thetypeofavariableisthetypeofthevalueitrefersto.
> > >t y p e ( m e s s a g e ) < t y p e' s t r ' > > > >t y p e ( n ) < t y p e' i n t ' > > > >t y p e ( p i ) < t y p e' f l o a t ' >
Exercise1 Ifyoutypeanintegerwithaleadingzero,youmightgetaconfusingerror:
> > >z i p c o d e=0 2 4 9 2 ^ S y n t a x E r r o r :i n v a l i dt o k e n
Othernumberseemtowork,buttheresultsarebizarre:
en.wikibooks.org/wiki/Think_Python/Print_version
16/282
10/24/13
Canyoufigureoutwhatisgoingon?Hint:printthevalues 0 1 , 0 1 0 , 0 1 0 0 and 0 1 0 0 0 .
Variablenamesandkeywords
Programmersgenerallychoosenamesfortheirvariablesthataremeaningfultheydocumentwhatthevariableisusedfor. Variablenamescanbearbitrarilylong.Theycancontainbothlettersandnumbers,buttheyhavetobeginwithaletter.Itislegaltouseuppercaseletters,but itisagoodideatobeginvariablenameswithalowercaseletter(you'llseewhylater). Theunderscorecharacter(_ )canappearinaname.Itisoftenusedinnameswithmultiplewords,suchas m y _ n a m e or a i r s p e e d _ o f _ u n l a d e n _ s w a l l o w . Ifyougiveavariableanillegalname,yougetasyntaxerror:
> > >7 6 t r o m b o n e s=' b i gp a r a d e ' S y n t a x E r r o r :i n v a l i ds y n t a x > > >m o r e @=1 0 0 0 0 0 0 S y n t a x E r r o r :i n v a l i ds y n t a x > > >c l a s s=' A d v a n c e dT h e o r e t i c a lZ y m u r g y ' S y n t a x E r r o r :i n v a l i ds y n t a x
7 6 t r o m b o n e s isillegalbecauseitdoesnotbeginwithaletter. m o r e @ isillegalbecauseitcontainsanillegalcharacter, @ .Butwhat'swrongwith c l a s s ?
a s s e r t e l s e b r e a k c l a s s
p a s s y i e l d
e x c e p ti m p o r tp r i n t e x e c i n r a i s e r e t u r n
c o n t i n u ef i n a l l yi s d e f f o r
l a m b d at r y
Youmightwanttokeepthislisthandy.Iftheinterpretercomplainsaboutoneofyourvariablenamesandyoudon'tknowwhy,seeifitisonthislist.
en.wikibooks.org/wiki/Think_Python/Print_version 17/282
10/24/13
youcanseethat y i e l d hasbeenrecognizedasakeywordandnotasanordinaryvariable,sinceitiscoloredorange.
Statements
AstatementisaunitofcodethatthePythoninterpretercanexecute.Wehaveseentwokindsofstatements:printandassignment. Whenyoutypeastatementininteractivemode,theinterpreterexecutesitanddisplaystheresult,ifthereisone. Ascriptusuallycontainsasequenceofstatements.Ifthereismorethanonestatement,theresultsappearoneatatimeasthestatementsexecute. Forexample,thescript
p r i n t1 x=2 p r i n tx
producestheoutput
1 2
Theassignmentstatementproducesnooutput.
Operatorsandoperands
Operatorsarespecialsymbolsthatrepresentcomputationslikeadditionandmultiplication.Thevaluestheoperatorisappliedtoarecalled operands. Theoperators + , , * , / and * * performaddition,subtraction,multiplication,divisionandexponentiation,asinthefollowingexamples:
2 0 + 3 2 h o u r 1 h o u r * 6 0 + m i n u t e m i n u t e / 6 0 5 * * 2 ( 5 + 9 ) * ( 1 5 7 )
10/24/13
Thedivisionoperatormightnotdowhatyouexpect:
> > >m i n u t e=5 9 > > >m i n u t e / 6 0 0
Expressions
An expressionisacombinationofvalues,variables,andoperators.Avalueallbyitselfisconsideredanexpression,andsoisavariable,sothefollowingare alllegalexpressions(assumingthatthevariable x hasbeenassignedavalue):
1 7 x x+1 7
Ifyoutypeanexpressionininteractivemode,theinterpreter evaluatesitanddisplaystheresult:
> > >1+1 2
en.wikibooks.org/wiki/Think_Python/Print_version
19/282
10/24/13
Nowputthesamestatementsintoascriptandrunit.Whatistheoutput?Modifythescriptbytransformingeachexpressionintoaprintstatementandthen runitagain.
Orderofoperations
Whenmorethanoneoperatorappearsinanexpression,theorderofevaluationdependsonthe rulesofprecedence.Formathematicaloperators,Python followsmathematicalconvention.Theacronym PEMDAS isausefulwaytoremembertherules: P arentheseshavethehighestprecedenceandcanbeusedtoforceanexpressiontoevaluateintheorderyouwant.Sinceexpressionsinparentheses areevaluatedfirst, 2*( 3 1 ) is4,and ( 1 + 1 ) * * ( 5 2 ) is8.Youcanalsouseparenthesestomakeanexpressioneasiertoread,asin ( m i n u t e*1 0 0 )/6 0 ,even ifitdoesn'tchangetheresult. E xponentiationhasthenexthighestprecedence,so 2 * * 1 + 1 is3,not4,and 3 * 1 * * 3 is3,not27. Multiplicationand Divisionhavethesameprecedence,whichishigherthan Additionand S ubtraction,whichalsohavethesameprecedence.So 2 * 3 1 is 5,not4,and 6 + 4 / 2 is8,not5. Operatorswiththesameprecedenceareevaluatedfromlefttoright.Sointheexpression d e g r e e s/2*p i ,thedivisionhappensfirstandtheresultis multipliedby p i .Todivideby2,youcanreordertheoperandsoruseparentheses.
Stringoperations
Ingeneral,youcannotperformmathematicaloperationsonstrings,evenifthestringslooklikenumbers,sothefollowingareillegal:
' 2 ' ' 1 ' ' e g g s ' / ' e a s y ' ' t h i r d ' * ' ac h a r m '
Theoutputofthisprogramis t h r o a t w a r b l e r . The * operatoralsoworksonstringsitperformsrepetition.Forexample, S p a m * 3 is ' S p a m S p a m S p a m ' .Ifoneoftheoperandsisastring,theotherhastobean integer. Thisuseof + and * makessensebyanalogywithadditionandmultiplication.Justas 4 * 3 isequivalentto 4 + 4 + 4 ,weexpect ' S p a m ' * 3 tobethesameas ' S p a m ' + ' S p a m ' + ' S p a m ' ,anditis.Ontheotherhand,thereisasignificantwayinwhichstringconcatenationandrepetitionaredifferentfromintegeradditionand multiplication.Canyouthinkofapropertythatadditionhasthatstringconcatenationdoesnot?
Comments
en.wikibooks.org/wiki/Think_Python/Print_version 20/282
10/24/13
Inthiscase,thecommentappearsonalinebyitself.Youcanalsoputcommentsattheendofaline:
p e r c e n t a g e=( m i n u t e*1 0 0 )/6 0 #p e r c e n t a g eo fa nh o u r
Thiscommentcontainsusefulinformationthatisnotinthecode:
v=5 #v e l o c i t yi nm e t e r s / s e c o n d .
Goodvariablenamescanreducetheneedforcomments,butlongnamescanmakecomplexexpressionshardtoread,sothereisatradeoff.
Debugging
Atthispointthesyntaxerroryouaremostlikelytomakeisanillegalvariablename,like c l a s s and y i e l d ,whicharekeywords,or o d d ~ j o b and U S $ ,whichcontain illegalcharacters. Ifyouputaspaceinavariablename,Pythonthinksitistwooperandswithoutanoperator:
> > >b a dn a m e=5 S y n t a x E r r o r :i n v a l i ds y n t a x
10/24/13
Theruntimeerroryouaremostlikelytomakeisausebeforedefthatis,tryingtouseavariablebeforeyouhaveassignedavalue.Thiscanhappenifyou spellavariablenamewrong:
> > >p r i n c i p a l=3 2 7 . 6 8 > > >i n t e r e s t=p r i n c i p l e*r a t e N a m e E r r o r :n a m e' p r i n c i p l e 'i sn o td e f i n e d
Butthedivisionhappensfirst,soyouwouldget/2,whichisnotthesamething!ThereisnowayforPythontoknowwhatyoumeanttowrite,sointhis caseyoudontgetanerrormessageyoujustgetthewronganswer.
Glossary
value: Oneofthebasicunitsofdata,likeanumberorstring,thataprogrammanipulates. type: Acategoryofvalues.Thetypeswehaveseensofarareintegers(type i n t ),floatingpointnumbers(type f l o a t ),andstrings(type s t r ). integer: Atypethatrepresentswholenumbers. floatingpoint: Atypethatrepresentsnumberswithfractionalparts. string: Atypethatrepresentssequencesofcharacters. variable: Anamethatreferstoavalue. statement: Asectionofcodethatrepresentsacommandoraction.Sofar,thestatementswehaveseenareassignmentsandprintstatements. assignment: Astatementthatassignsavaluetoavariable. statediagram: Agraphicalrepresentationofasetofvariablesandthevaluestheyreferto. keyword:
en.wikibooks.org/wiki/Think_Python/Print_version 22/282
10/24/13
Areservedwordthatisusedbythecompilertoparseaprogramyoucannotusekeywordslike i f , d e f ,and w h i l e asvariablenames. operator: Aspecialsymbolthatrepresentsasimplecomputationlikeaddition,multiplication,orstringconcatenation. operand: Oneofthevaluesonwhichanoperatoroperates. floordivision: Theoperationthatdividestwonumbersandchopsoffthefractionpart. expression: Acombinationofvariables,operators,andvaluesthatrepresentsasingleresultvalue. evaluate: Tosimplifyanexpressionbyperformingtheoperationsinordertoyieldasinglevalue. rulesofprecedence: Thesetofrulesgoverningtheorderinwhichexpressionsinvolvingmultipleoperatorsandoperandsareevaluated. concatenate: Tojointwooperandsendtoend. comment: Informationinaprogramthatismeantforotherprogrammers(oranyonereadingthesourcecode)andhasnoeffectontheexecutionoftheprogram.
Exercises
Exercise3 Assumethatweexecutethefollowingassignmentstatements:
w i d t h=1 7 h e i g h t=1 2 . 0 d e l i m i t e r=' . '
Foreachofthefollowingexpressions,writethevalueoftheexpressionandthetype(ofthevalueoftheexpression).
w i d t h / 2 w i d t h / 2 . 0 h e i g h t / 3 1+2*5 d e l i m i t e r*5
UsethePythoninterpretertocheckyouranswers.
en.wikibooks.org/wiki/Think_Python/Print_version
23/282
10/24/13
Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.
Functions
Functioncalls
Inthecontextofprogramming,a functionisanamedsequenceofstatementsthatperformsacomputation.Whenyoudefineafunction,youspecifythe nameandthesequenceofstatements.Later,youcan"call"thefunctionbyname.Wehavealreadyseenoneexampleofa functioncall :
Typeconversionfunctions
Pythonprovidesbuiltinfunctionsthatconvertvaluesfromonetypetoanother.Theintfunctiontakesanyvalueandconvertsittoaninteger,ifitcan,or complainsotherwise:
en.wikibooks.org/wiki/Think_Python/Print_version
24/282
10/24/13
> > >i n t ( ' 3 2 ' ) 3 2 > > >i n t ( ' H e l l o ' ) V a l u e E r r o r :i n v a l i dl i t e r a lf o ri n t ( ) :H e l l o
intcanconvertfloatingpointvaluestointegers,butitdoesn'troundoffitchopsoffthefractionpart:
> > >i n t ( 3 . 9 9 9 9 9 ) 3 > > >i n t ( 2 . 3 ) 2
floatconvertsintegersandstringstofloatingpointnumbers:
> > >f l o a t ( 3 2 ) 3 2 . 0 > > >f l o a t ( ' 3 . 1 4 1 5 9 ' ) 3 . 1 4 1 5 9
Finally,strconvertsitsargumenttoastring:
> > >s t r ( 3 2 ) ' 3 2 ' > > >s t r ( 3 . 1 4 1 5 9 ) ' 3 . 1 4 1 5 9 '
Mathfunctions
Pythonhasamathmodulethatprovidesmostofthefamiliarmathematicalfunctions.A moduleisafilethatcontainsacollectionofrelatedfunctions. Beforewecanusethemodule,wehavetoimportit:
> > >i m p o r tm a t h
Thisstatementcreatesa moduleobjectnamedmath.Ifyouprintthemoduleobject,yougetsomeinformationaboutit:
10/24/13
> > >r a t i o=s i g n a l _ p o w e r/n o i s e _ p o w e r > > >d e c i b e l s=1 0*m a t h . l o g 1 0 ( r a t i o ) > > >r a d i a n s=0 . 7 > > >h e i g h t=m a t h . s i n ( r a d i a n s )
> > >d e g r e e s=4 5 > > >r a d i a n s=d e g r e e s/3 6 0 . 0*2*m a t h . p i > > >m a t h . s i n ( r a d i a n s ) 0 . 7 0 7 1 0 6 7 8 1 1 8 7
Theexpressionmath.pigetsthevariablepifromthemathmodule.Thevalueofthisvariableisanapproximationof,accuratetoabout15digits. Ifyouknowyourtrigonometry,youcancheckthepreviousresultbycomparingittothesquarerootoftwodividedbytwo:
Composition
Sofar,wehavelookedattheelementsofaprogramvariables,expressions,andstatementsinisolation,withouttalkingabouthowtocombinethem. Oneofthemostusefulfeaturesofprogramminglanguagesistheirabilitytotakesmallbuildingblocksand composethem.Forexample,theargumentofa functioncanbeanykindofexpression,includingarithmeticoperators:
en.wikibooks.org/wiki/Think_Python/Print_version 26/282
10/24/13
Andevenfunctioncalls:
x=m a t h . e x p ( m a t h . l o g ( x + 1 ) )
Almostanywhereyoucanputavalue,youcanputanarbitraryexpression,withoneexception:theleftsideofanassignmentstatementhastobeavariable name.Anyotherexpressionontheleftsideisasyntaxerror.
> > >m i n u t e s=h o u r s*6 0 > > >h o u r s*6 0=m i n u t e s S y n t a x E r r o r :c a n ' ta s s i g nt oo p e r a t o r #r i g h t #w r o n g !
Addingnewfunctions
Sofar,wehaveonlybeenusingthefunctionsthatcomewithPython,butitisalsopossibletoaddnewfunctions.A functiondefinitionspecifiesthenameof anewfunctionandthesequenceofstatementsthatexecutewhenthefunctioniscalled. Hereisanexample:
d e fp r i n t _ l y r i c s ( ) : p r i n t" I ' mal u m b e r j a c k ,a n dI ' mo k a y . " p r i n t" Is l e e pa l ln i g h ta n dIw o r ka l ld a y . "
defisakeywordthatindicatesthatthisisafunctiondefinition.Thenameofthefunctionis p r i n t _ l y r i c s .Therulesforfunctionnamesarethesameasfor variablenames:letters,numbersandsomepunctuationmarksarelegal,butthefirstcharactercan'tbeanumber.Youcan'tuseakeywordasthenameofa function,andyoushouldavoidhavingavariableandafunctionwiththesamename. Theemptyparenthesesafterthenameindicatethatthisfunctiondoesn'ttakeanyarguments. Thefirstlineofthefunctiondefinitioniscalledthe headertherestiscalledthe body.Theheaderhastoendwithacolonandthebodyhastobeindented. Byconvention,theindentationisalwaysfourspaces(seeSection).Thebodycancontainanynumberofstatements. Thestringsintheprintstatementsareenclosedindoublequotes.Singlequotesanddoublequotesdothesamethingmostpeopleusesinglequotesexcept incaseslikethiswhereasinglequote(whichisalsoanapostrophe)appearsinthestring. Ifyoutypeafunctiondefinitionininteractivemode,theinterpreterprintsellipses(... )toletyouknowthatthedefinitionisn'tcomplete:
> > >d e fp r i n t _ l y r i c s ( ) : . . . p r i n t" I ' mal u m b e r j a c k ,a n dI ' mo k a y . "
en.wikibooks.org/wiki/Think_Python/Print_version 27/282
10/24/13
. . . . . .
Toendthefunction,youhavetoenteranemptyline(thisisnotnecessaryinascript). Definingafunctioncreatesavariablewiththesamename.
> > >p r i n tp r i n t _ l y r i c s < f u n c t i o np r i n t _ l y r i c sa t0 x b 7 e 9 9 e 9 c > > > >p r i n tt y p e ( p r i n t _ l y r i c s ) < t y p e' f u n c t i o n ' >
Onceyouhavedefinedafunction,youcanuseitinsideanotherfunction.Forexample,torepeatthepreviousrefrain,wecouldwriteafunctioncalled r e p e a t _ l y r i c s :
d e fr e p e a t _ l y r i c s ( ) : p r i n t _ l y r i c s ( ) p r i n t _ l y r i c s ( )
Andthencall r e p e a t _ l y r i c s :
> > >r e p e a t _ l y r i c s ( ) I ' mal u m b e r j a c k ,a n dI ' mo k a y . Is l e e pa l ln i g h ta n dIw o r ka l ld a y . I ' mal u m b e r j a c k ,a n dI ' mo k a y . Is l e e pa l ln i g h ta n dIw o r ka l ld a y .
Butthat'snotreallyhowthesonggoes.
en.wikibooks.org/wiki/Think_Python/Print_version 28/282
10/24/13
Definitionsanduses
Pullingtogetherthecodefragmentsfromtheprevioussection,thewholeprogramlookslikethis:
Exercise1
Movethelastlineofthisprogramtothetop,sothefunctioncallappearsbeforethedefinitions.Runtheprogramandseewhaterrormessageyouget.
Exercise2
Movethefunctioncallbacktothebottomandmovethedefinitionof p r i n t _ l y r i c s afterthedefinitionof r e p e a t _ l y r i c s .Whathappenswhenyourunthisprogram?
Flowofexecution
Inordertoensurethatafunctionisdefinedbeforeitsfirstuse,youhavetoknowtheorderinwhichstatementsareexecuted,whichiscalledthe flowof execution. Executionalwaysbeginsatthefirststatementoftheprogram.Statementsareexecutedoneatatime,inorderfromtoptobottom. Functiondefinitionsdonotaltertheflowofexecutionoftheprogram,butrememberthatstatementsinsidethefunctionarenotexecuteduntilthefunctionis called. Afunctioncallislikeadetourintheflowofexecution.Insteadofgoingtothenextstatement,theflowjumpstothebodyofthefunction,executesallthe statementsthere,andthencomesbacktopickupwhereitleftoff.
en.wikibooks.org/wiki/Think_Python/Print_version 29/282
10/24/13
Parametersandarguments
Someofthebuiltinfunctionswehaveseenrequirearguments.Forexample,whenyoucallmath.sinyoupassanumberasanargument.Somefunctions takemorethanoneargument:math.powtakestwo,thebaseandtheexponent. Insidethefunction,theargumentsareassignedtovariablescalled parameters.Hereisanexampleofauserdefinedfunctionthattakesanargument:
d e fp r i n t _ t w i c e ( b r u c e ) : p r i n tb r u c e p r i n tb r u c e
Thisfunctionassignstheargumenttoaparameternamedbruce.Whenthefunctioniscalled,itprintsthevalueoftheparameter(whateveritis)twice. Thisfunctionworkswithanyvaluethatcanbeprinted.
> > >p r i n t _ t w i c e ( ' S p a m ' ) S p a m S p a m > > >p r i n t _ t w i c e ( 1 7 ) 1 7 1 7 > > >p r i n t _ t w i c e ( m a t h . p i ) 3 . 1 4 1 5 9 2 6 5 3 5 9 3 . 1 4 1 5 9 2 6 5 3 5 9
Thesamerulesofcompositionthatapplytobuiltinfunctionsalsoapplytouserdefinedfunctions,sowecanuseanykindofexpressionasanargumentfor p r i n t _ t w i c e :
en.wikibooks.org/wiki/Think_Python/Print_version 30/282
10/24/13
> > >m i c h a e l=' E r i c ,t h eh a l fab e e . ' > > >p r i n t _ t w i c e ( m i c h a e l ) E r i c ,t h eh a l fab e e . E r i c ,t h eh a l fab e e .
Variablesandparametersarelocal
Whenyoucreateavariableinsideafunction,itis local ,whichmeansthatitonlyexistsinsidethefunction.Forexample:
d e fc a t _ t w i c e ( p a r t 1 ,p a r t 2 ) : c a t=p a r t 1+p a r t 2 p r i n t _ t w i c e ( c a t )
Thisfunctiontakestwoarguments,concatenatesthem,andprintstheresulttwice.Hereisanexamplethatusesit:
> > >l i n e 1=' B i n gt i d d l e' > > >l i n e 2=' t i d d l eb a n g . ' > > >c a t _ t w i c e ( l i n e 1 ,l i n e 2 )
en.wikibooks.org/wiki/Think_Python/Print_version 31/282
10/24/13
B i n gt i d d l et i d d l eb a n g . B i n gt i d d l et i d d l eb a n g .
When c a t _ t w i c e terminates,thevariablecatisdestroyed.Ifwetrytoprintit,wegetanexception:
Parametersarealsolocal.Forexample,outside p r i n t _ t w i c e ,thereisnosuchthingasbruce.
Stackdiagrams
Tokeeptrackofwhichvariablescanbeusedwhere,itissometimesusefultodrawa stackdiagram.Likestatediagrams,stackdiagramsshowthevalueof eachvariable,buttheyalsoshowthefunctioneachvariablebelongsto. Eachfunctionisrepresentedbya frame.Aframeisaboxwiththenameofafunctionbesideitandtheparametersandvariablesofthefunctioninsideit.The stackdiagramforthepreviousexamplelookslikethis: File:Book004.pngTheframesarearrangedinastackthatindicateswhichfunctioncalledwhich,andsoon.Inthisexample, p r i n t _ t w i c e wascalledby c a t _ t w i c e ,and c a t _ t w i c e wascalledby _ _ m a i n _ _ ,whichisaspecialnameforthetopmostframe.Whenyoucreateavariableoutsideofanyfunction, itbelongsto _ _ m a i n _ _ . Eachparameterreferstothesamevalueasitscorrespondingargument.So,part1hasthesamevalueasline1,part2hasthesamevalueasline2,andbruce hasthesamevalueascat. Ifanerroroccursduringafunctioncall,Pythonprintsthenameofthefunction,andthenameofthefunctionthatcalledit,andthenameofthefunctionthat called that ,allthewaybackto _ _ m a i n _ _ . Forexample,ifyoutrytoaccesscatfromwithin
p r i n t _ t w i c e ,yougetaNameError:
T r a c e b a c k( i n n e r m o s tl a s t ) :
en.wikibooks.org/wiki/Think_Python/Print_version 32/282
10/24/13
Fruitfulfunctionsandvoidfunctions
Someofthefunctionsweareusing,suchasthemathfunctions,yieldresultsforlackofabettername,Icallthem fruitful functions.Otherfunctions,like p r i n t _ t w i c e ,performanactionbutdon'treturnavalue.Theyarecalled voidfunctions. Whenyoucallafruitfulfunction,youalmostalwayswanttodosomethingwiththeresultforexample,youmightassignittoavariableoruseitaspartofan expression:
Whenyoucallafunctionininteractivemode,Pythondisplaystheresult:
Butinascript,ifyoucallafruitfulfunctionallbyitself,thereturnvalueislostforever!
m a t h . s q r t ( 5 )
en.wikibooks.org/wiki/Think_Python/Print_version
33/282
10/24/13
Thefunctionswehavewrittensofarareallvoid.Wewillstartwritingfruitfulfunctionsinafewchapters.
Whyfunctions?
Itmaynotbeclearwhyitisworththetroubletodivideaprogramintofunctions.Thereareseveralreasons: Creatinganewfunctiongivesyouanopportunitytonameagroupofstatements,whichmakesyourprogrameasiertoreadanddebug. Functionscanmakeaprogramsmallerbyeliminatingrepetitivecode.Later,ifyoumakeachange,youonlyhavetomakeitinoneplace. Dividingalongprogramintofunctionsallowsyoutodebugthepartsoneatatimeandthenassemblethemintoaworkingwhole. Welldesignedfunctionsareoftenusefulformanyprograms.Onceyouwriteanddebugone,youcanreuseit.
Debugging
Ifyouareusingatexteditortowriteyourscripts,youmightrunintoproblemswithspacesandtabs.Thebestwaytoavoidtheseproblemsistousespaces exclusively(notabs).MosttexteditorsthatknowaboutPythondothisbydefault,butsomedon't. Tabsandspacesareusuallyinvisible,whichmakesthemhardtodebug,sotrytofindaneditorthatmanagesindentationforyou.
en.wikibooks.org/wiki/Think_Python/Print_version
34/282
10/24/13
Glossary
function:Anamedsequenceofstatementsthatperformssome usefuloperation.Functionsmayormaynottakeargumentsandmayormaynotproducearesult. functiondefinition:Astatementthatcreatesanewfunction, specifyingitsname,parameters,andthestatementsitexecutes. functionobject:Avaluecreatedbyafunctiondefinition. Thenameofthefunctionisavariablethatreferstoafunctionobject. header:Thefirstlineofafunctiondefinition. body:Thesequenceofstatementsinsideafunctiondefinition. parameter:Anameusedinsideafunctiontorefertothevalue passedasanargument. functioncall:Astatementthatexecutesafunction.It consistsofthefunctionnamefollowedbyanargumentlist. argument:Avalueprovidedtoafunctionwhenthefunctioniscalled. Thisvalueisassignedtothecorrespondingparameterinthefunction. localvariable:Avariabledefinedinsideafunction.Alocal variablecanonlybeusedinsideitsfunction.
en.wikibooks.org/wiki/Think_Python/Print_version 35/282
10/24/13
returnvalue:Theresultofafunction.Ifafunctioncall isusedasanexpression,thereturnvalueisthevalueoftheexpression. fruitfulfunction:Afunctionthatreturnsavalue. voidfunction:Afunctionthatdoesn'treturnavalue. module:Afilethatcontainsa collectionofrelatedfunctionsandotherdefinitions. importstatement:Astatementthatreadsamodulefileandcreates amoduleobject. moduleobject:Avaluecreatedbyanimportstatement thatprovidesaccesstothevaluesdefinedinamodule. dotnotation:Thesyntaxforcallingafunctioninanother modulebyspecifyingthemodulenamefollowedbyadot(period)andthefunctionname. composition:Usinganexpressionaspartofalargerexpression, orastatementaspartofalargerstatement. flowofexecution:Theorderinwhichstatementsareexecutedduring aprogramrun. stackdiagram:Agraphicalrepresentationofastackoffunctions, theirvariables,andthevaluestheyreferto. frame:Aboxinastackdiagramthatrepresentsafunctioncall. Itcontainsthelocalvariablesandparametersofthefunction. traceback:Alistofthefunctionsthatareexecuting, printedwhenanexceptionoccurs.
Exercises
en.wikibooks.org/wiki/Think_Python/Print_version 36/282
10/24/13
Exercise3
Pythonprovidesabuiltinfunctioncalledlenthat returnsthelengthofastring,sothevalueof l e n ( ' a l l e n ' ) is5. Writeafunctionnamed r i g h t _ j u s t i f y thattakesastringnamedsasaparameterandprintsthestringwithenoughleadingspacessothatthelastletterofthe stringisincolumn70ofthedisplay.
' ' > > >r i g h t _ j u s t i f y ( ' a l l e n ' ) a l l e n ' '
Exercise4
Afunctionobjectisavalueyoucanassigntoavariableorpassasanargument.Forexample, d o _ t w i c e isafunctionthattakesafunctionobjectasan argumentandcallsittwice:
1. Typethisexampleintoascriptandtestit. 2. Modify d o _ t w i c e sothatittakestwoarguments,afunctionobjectandavalue,andcallsthefunctiontwice,passingthevalueasanargument. 3. Writeamoregeneralversionof p r i n t _ s p a m ,called p r i n t _ t w i c e ,thattakesastringasaparameterandprintsittwice. 4. Usethemodifiedversionof d o _ t w i c e tocall p r i n t _ t w i c e twice,passing ' s p a m ' asanargument. 5. Defineanewfunctioncalled d o _ f o u r thattakesafunctionobjectandavalueandcallsthefunctionfourtimes,passingthevalueasaparameter.There shouldbeonlytwostatementsinthebodyofthisfunction,notfour. Youcanseemysolutionatthinkpython.com/code/do_four.py.
en.wikibooks.org/wiki/Think_Python/Print_version 37/282
10/24/13
Exercise5
Thisexercise' canbedoneusingonlythestatementsandotherfeatureswehavelearnedsofar. 1. Writeafunctionthatdrawsagridlikethefollowing:
' ' +----+----+ | | | | | | | | | | | | +----+----+ | | | | | | | | | | | | +----+----+ ' '
Hint:toprintmorethanonevalueonaline,youcanprintacommaseparatedsequence:
' ' p r i n t' + ' ,' '' '
Ifthesequenceendswithacomma,Pythonleavesthelineunfinished,sothevalueprintednextappearsonthesameline.
' ' p r i n t' + ' ,p r i n t' '' '
Casestudy:interfacedesign
TurtleWorld
en.wikibooks.org/wiki/Think_Python/Print_version
Toaccompanythisbook,IhavewrittenasuiteofmodulescalledSwampy.OneofthesemodulesisTurtleWorld,whichprovidesasetoffunctionsfordrawing 38/282
10/24/13
TurtleWorldprovidesseveralturtlesteeringfunctions: f d and b k forforwardandbackward,and l t and r t forleftandrightturns.Also,eachTurtleisholdinga pen,whichiseitherdownorupifthepenisdown,theTurtleleavesatrailwhenitmoves.Thefunctions p u and p d standforpenupandpendown. Todrawarightangle,addtheselinestotheprogram(aftercreating b o b andbeforecalling w a i t _ f o r _ u s e r ):
f d ( b o b ,1 0 0 ) r t ( b o b ) f d ( b o b ,1 0 0 )
Simplerepetition
en.wikibooks.org/wiki/Think_Python/Print_version 39/282
10/24/13
Chancesareyouwrotesomethinglikethis(leavingoutthecodethatcreatesTurtleWorldandwaitsfortheuser):
f d ( b o b ,1 0 0 ) l t ( b o b ) f d ( b o b ,1 0 0 ) l t ( b o b ) f d ( b o b ,1 0 0 ) l t ( b o b ) f d ( b o b ,1 0 0 )
Youshouldseesomethinglikethis:
H e l l o ! H e l l o ! H e l l o ! H e l l o !
10/24/13
Exercises
ThefollowingisaseriesofexercisesusingTurtleWorld.Theyaremeanttobefun,buttheyhaveapoint,too.Whileyouareworkingonthem,thinkabout whatthepointis. Thefollowingsectionshavesolutionstotheexercises,sodontlookuntilyouhavefinished(oratleasttried). Writeafunctioncalled s q u a r e thattakesaparameter named t ,whichisaturtle.Itshouldusetheturtletodrawasquare.Writeafunctioncallthatpasses b o b asanargumentto s q u a r e ,andthenruntheprogram again. Addanotherparameter,named l e n g t h ,to s q u a r e . Modifythebodysolengthofthesidesis l e n g t h ,andthenmodifythefunctioncalltoprovideasecondargument.Runtheprogramagain.Testyourprogram witharangeofvaluesfor l e n g t h . Thefunctions l t and r t make90degreeturnsby default,butyoucanprovideasecondargumentthatspecifiesthenumberofdegrees.Forexample, l t ( b o b ,4 5 ) turns b o b 45degreestotheleft.Makeacopyof s q u a r e andchangethenameto p o l y g o n .Addanotherparameternamed n andmodifythebodysoitdrawsannsidedregularpolygon.Hint:Theanglesofann sidedregularpolygonare360.0/ ndegrees.
Hint:figureoutthecircumferenceofthecircleandmakesurethat l e n g t h*n=c i r c u m f e r e n c e . Anotherhint:if b o b istooslowforyou,youcanspeedhimupbychanging b o b . d e l a y ,whichisthetimebetweenmoves,inseconds. b o b . d e l a y=0 . 0 1 oughttoget himmoving. Makeamoregeneralversionof c i r c l e called a r c
en.wikibooks.org/wiki/Think_Python/Print_version 41/282
10/24/13
Encapsulation
Thefirstexerciseasksyoutoputyoursquaredrawingcodeintoafunctiondefinitionandthencallthefunction,passingtheturtleasaparameter.Hereisa solution:
d e fs q u a r e ( t ) : f o rii nr a n g e ( 4 ) : f d ( t ,1 0 0 ) l t ( t ) s q u a r e ( b o b )
Theinnermoststatements, f d and l t areindentedtwicetoshowthattheyareinsidethe f o r loop,whichisinsidethefunctiondefinition.Thenextline, s q u a r e ( b o b ) ,isflushwiththeleftmargin,sothatistheendofboththe f o r loopandthefunctiondefinition. Insidethefunction, t referstothesameturtle b o b refersto,so l t ( t ) hasthesameeffectas l t ( b o b ) .Sowhynotcalltheparameter b o b ?Theideaisthat t canbe anyturtle,notjust b o b ,soyoucouldcreateasecondturtleandpassitasanargumentto s q u a r e :
r a y=T u r t l e ( ) s q u a r e ( r a y )
Generalization
Thenextstepistoadda l e n g t h parameterto s q u a r e .Hereisasolution:
d e fs q u a r e ( t ,l e n g t h ) : f o rii nr a n g e ( 4 ) : f d ( t ,l e n g t h ) l t ( t ) s q u a r e ( b o b ,1 0 0 )
10/24/13
Thisdrawsa7sidedpolygonwithsidelength70.Ifyouhavemorethanafewnumericarguments,itiseasytoforgetwhattheyare,orwhatordertheyshould bein.Itislegal,andsometimeshelpful,toincludethenamesoftheparametersintheargumentlist:
p o l y g o n ( b o b ,n = 7 ,l e n g t h = 7 0 )
Interfacedesign
Thenextstepistowrite c i r c l e ,whichtakesaradius, r ,asaparameter.Hereisasimplesolutionthatuses p o l y g o n todrawa50sidedpolygon:
d e fc i r c l e ( t ,r ) : c i r c u m f e r e n c e=2*m a t h . p i*r n=5 0 l e n g t h=c i r c u m f e r e n c e/n p o l y g o n ( t ,n ,l e n g t h )
approximatesacirclewithradius r . Onelimitationofthissolutionisthat n isaconstant,whichmeansthatforverybigcircles,thelinesegmentsaretoolong,andforsmallcircles,wewastetime drawingverysmallsegments.Onesolutionwouldbetogeneralizethefunctionbytaking n asaparameter.Thiswouldgivetheuser(whoevercalls c i r c l e )more control,buttheinterfacewouldbelessclean. The interfaceofafunctionisasummaryofhowitisused:whataretheparameters?Whatdoesthefunctiondo?Andwhatisthereturnvalue?Aninterfaceis cleanifitisassimpleaspossible,butnotsimpler.(Einstein) Inthisexample, r belongsintheinterfacebecauseitspecifiesthecircletobedrawn. n islessappropriatebecauseitpertainstothedetailsof howthecircle shouldberendered.
en.wikibooks.org/wiki/Think_Python/Print_version 43/282
10/24/13
Ratherthanclutteruptheinterface,itisbettertochooseanappropriatevalueof n dependingon c i r c u m f e r e n c e :
d e fc i r c l e ( t ,r ) : c i r c u m f e r e n c e=2*m a t h . p i*r n=i n t ( c i r c u m f e r e n c e/3 )+1 l e n g t h=c i r c u m f e r e n c e/n p o l y g o n ( t ,n ,l e n g t h )
Refactoring
WhenIwrote c i r c l e ,Iwasabletoreuse p o l y g o n becauseamanysidedpolygonisagoodapproximationofacircle.But a r c isnotascooperativewecantuse p o l y g o n or c i r c l e todrawanarc. Onealternativeistostartwithacopyof p o l y g o n andtransformitinto a r c .Theresultmightlooklikethis:
d e fa r c ( t ,r ,a n g l e ) : a r c _ l e n g t h=r*m a t h . r a d i a n s ( a n g l e ) n=i n t ( a r c _ l e n g t h/3 )+1 s t e p _ l e n g t h=a r c _ l e n g t h/n s t e p _ a n g l e=f l o a t ( a n g l e )/n f o rii nr a n g e ( n ) : f d ( t ,s t e p _ l e n g t h ) l t ( t ,s t e p _ a n g l e )
10/24/13
Finally,wecanrewrite c i r c l e touse a r c :
d e fc i r c l e ( t ,r ) : a r c ( t ,r ,3 6 0 )
Adevelopmentplan
A developmentplanisaprocessforwritingprograms.Theprocessweusedinthiscasestudyisencapsulationandgeneralization.Thestepsofthisprocess are: Startbywritingasmallprogramwithnofunctiondefinitions. Onceyougettheprogramworking,encapsulateitinafunction andgiveitaname. Generalizethefunctionbyaddingappropriateparameters. Repeatsteps13untilyouhaveasetofworkingfunctions. Copyandpasteworkingcodetoavoidretyping(andredebugging). Lookforopportunitiestoimprovetheprogrambyrefactoring. Forexample,ifyouhavesimilarcodeinseveralplaces,considerfactoringitintoanappropriatelygeneralfunction. Thisprocesshassomedrawbackswewillseealternativeslaterbutitcanbeusefulifyoudontknowaheadoftimehowtodividetheprograminto functions.Thisapproachletsyoudesignasyougoalong.
docstring
en.wikibooks.org/wiki/Think_Python/Print_version
45/282
10/24/13
A docstringisastringatthebeginningofafunctionthatexplainstheinterface(docisshortfordocumentation).Hereisanexample:
d e fp o l y l i n e ( t ,l e n g t h ,n ,a n g l e ) : " " " D r a wnl i n es e g m e n t sw i t ht h eg i v e nl e n g t ha n d a n g l e( i nd e g r e e s )b e t w e e nt h e m . ti sat u r t l e . " " " f o rii nr a n g e ( n ) : f d ( t ,l e n g t h ) l t ( t ,a n g l e )
Debugging
Aninterfaceislikeacontractbetweenafunctionandacaller.Thecalleragreestoprovidecertainparametersandthefunctionagreestodocertainwork. Forexample, p o l y l i n e requiresfourarguments.ThefirsthastobeaTurtle(orsomeotherobjectthatworkswith f d and l t ).Thesecondhastobeanumber, anditshouldprobablybepositive,althoughitturnsoutthatthefunctionworksevenifitisnt.Thethirdargumentshouldbeaninteger r a n g e complains otherwise(dependingonwhichversionofPythonyouarerunning).Thefourthhastobeanumber,whichisunderstoodtobeindegrees. Theserequirementsarecalled preconditionsbecausetheyaresupposedtobetruebeforethefunctionstartsexecuting.Conversely,conditionsattheendof thefunctionare postconditions.Postconditionsincludetheintendedeffectofthefunction(likedrawinglinesegments)andanysideeffects(likemovingthe TurtleormakingotherchangesintheWorld). Preconditionsaretheresponsibilityofthecaller.Ifthecallerviolatesa(properlydocumented!)preconditionandthefunctiondoesntworkcorrectly,thebugis inthecaller,notthefunction.However,forpurposesofdebuggingitisoftenagoodideaforfunctionstochecktheirpreconditionsratherthanassumetheyare true.Ifeveryfunctionchecksitspreconditionsbeforestarting,thenifsomethinggoeswrong,youwillknowwhichfunctiontoblame.
Glossary
instance: Amemberofaset.TheTurtleWorldinthischapterisamemberofthesetofTurtleWorlds. loop: Apartofaprogramthatcanexecuterepeatedly. encapsulation: Theprocessoftransformingasequenceofstatementsintoafunctiondefinition.
en.wikibooks.org/wiki/Think_Python/Print_version 46/282
10/24/13
generalization: Theprocessofreplacingsomethingunnecessarilyspecific(likeanumber)withsomethingappropriatelygeneral(likeavariableorparameter). keywordargument: Anargumentthatincludesthenameoftheparameterasakeyword. interface: Adescriptionofhowtouseafunction,includingthenameanddescriptionsoftheargumentsandreturnvalue. developmentplan: Aprocessforwritingprograms. docstring: Astringthatappearsinafunctiondefinitiontodocumentthefunctionsinterface. precondition: Arequirementthatshouldbesatisfiedbythecallerbeforeafunctionstarts. postcondition: Arequirementthatshouldbesatisfiedbythefunctionbeforeitends.
Exercises
Exercise1 Downloadthecodeinthischapterfrom't h i n k p y t h o n . c o m / c o d e / p o l y g o n . p y '. Writeappropriatedocstringsfor'p o l y g o n ','a r c 'and 'c i r c l e '. Drawastackdiagramthatshowsthestateoftheprogram whileexecuting'c i r c l e ( b o b ,r a d i u s ) '.Youcandothearithmeticbyhandoradd'p r i n t 'statementstothecode. Theversionof'a r c 'inSection'4.7'isnot veryaccuratebecausethelinearapproximationofthecircleisalwaysoutsidethetruecircle.Asaresult,theturtleendsupafewunitsawayfromthecorrect destination.Mysolutionshowsawaytoreducetheeffectofthiserror.Readthecodeandseeifitmakessensetoyou.Ifyoudrawadiagram,youmightsee howitworks. Exercise2 Writeanappropriatelygeneralsetoffunctionsthat candrawflowerslikethis: <IMGSRC="book005.png"> Youcandownloadasolutionfrom't h i n k p y t h o n . c o m / c o d e / f l o w e r . p y '. Exercise3 Writeanappropriatelygeneralsetoffunctionsthat candrawshapeslikethis:
en.wikibooks.org/wiki/Think_Python/Print_version 47/282
10/24/13
<IMGSRC="book006.png"> Youcandownloadasolutionfrom't h i n k p y t h o n . c o m / c o d e / p i e . p y '. Exercise4 '' Thelettersofthealphabetcanbeconstructedfromamoderatenumberofbasicelements,likeverticalandhorizontallinesandafewcurves.Designafont thatcanbedrawnwithaminimalnumberofbasicelementsandthenwritefunctionsthatdrawlettersofthealphabet. Youshouldwriteonefunctionforeachletter,withnames d r a w _ a , d r a w _ b ,etc.,andputyourfunctionsinafilenamed'l e t t e r s . p y '.Youcandownloadaturtle typewriterfrom't h i n k p y t h o n . c o m / c o d e / t y p e w r i t e r . p y 'tohelpyoutestyourcode. Youcandownloadasolutionfrom't h i n k p y t h o n . c o m / c o d e / l e t t e r s . p y '.
Conditionalandrecursion
Modulusoperator
The modulusoperatorworksonintegersandyieldstheremainderwhenthefirstoperandisdividedbythesecond.InPython,themodulusoperatorisa percentsign(% ).Thesyntaxisthesameasforotheroperators:
> > >q u o t i e n t=7/ /3 > > >p r i n t ( q u o t i e n t ) 2 > > >r e m a i n d e r=7%3 > > >p r i n t ( r e m a i n d e r ) 1
So7dividedby3is2with1leftover. Themodulusoperatorturnsouttobesurprisinglyuseful.Forexample,youcancheckwhetheronenumberisdivisiblebyanotherif x%y iszero,then x is divisibleby y . Also,youcanextracttherightmostdigitordigitsfromanumber.Forexample, x%1 0 yieldstherightmostdigitof x (inbase10).Similarly x%1 0 0 yieldsthe lasttwodigits.
Booleanexpressions
A booleanexpressionisanexpressionthatiseithertrueorfalse.Thefollowingexamplesusetheoperator = = ,whichcomparestwooperandsandproduces T r u e iftheyareequaland F a l s e otherwise:
> > >5= =5 T r u e
en.wikibooks.org/wiki/Think_Python/Print_version 48/282
10/24/13
> > >t y p e ( T r u e ) < t y p e' b o o l ' > > > >t y p e ( F a l s e ) < t y p e' b o o l ' >
Logicaloperators
Therearethree logicaloperators: a n d , o r ,and n o t .Thesemantics(meaning)oftheseoperatorsissimilartotheirmeaninginEnglish.Forexample, x>0a n dx <1 0 istrueonlyif x isgreaterthan0 andlessthan10.
n % 2= =0o rn % 3= =0 istrueif eitheroftheconditionsistrue,thatis,ifthenumberisdivisibleby2 or3.
Thisflexibilitycanbeuseful,buttherearesomesubtletiestoitthatmightbeconfusing.Youmightwanttoavoidit(unlessyouknowwhatyouaredoing).
Conditionalexecution
Inordertowriteusefulprograms,wealmostalwaysneedtheabilitytocheckconditionsandchangethebehavioroftheprogramaccordingly. Conditional
en.wikibooks.org/wiki/Think_Python/Print_version
49/282
10/24/13
#n e e dt oh a n d l en e g a t i v ev a l u e s !
Alternativeexecution
Asecondformofthe i f statementis alternativeexecution,inwhichtherearetwopossibilitiesandtheconditiondetermineswhichonegetsexecuted.The syntaxlookslikethis:
i fx%2= =0 : p r i n t' xi se v e n ' e l s e : p r i n t' xi so d d '
Chainedconditionals
Sometimestherearemorethantwopossibilitiesandweneedmorethantwobranches.Onewaytoexpressacomputationlikethatisa chainedconditional :
i fx<y : p r i n t' xi sl e s st h a ny ' e l i fx>y : p r i n t' xi sg r e a t e rt h a ny ' e l s e : p r i n t' xa n dya r ee q u a l '
10/24/13
hastobeattheend,buttheredoesnthavetobeone.
i fc h o i c e= =' a ' : d r a w _ a ( ) e l i fc h o i c e= =' b ' : d r a w _ b ( ) e l i fc h o i c e= =' c ' : d r a w _ c ( )
Eachconditionischeckedinorder.Ifthefirstisfalse,thenextischecked,andsoon.Ifoneofthemistrue,thecorrespondingbranchexecutes,andthe statementends.Evenifmorethanoneconditionistrue,onlythefirsttruebranchexecutes.
Nestedconditionals
Oneconditionalcanalsobenestedwithinanother.Wecouldhavewrittenthetrichotomyexamplelikethis:
i fx= =y : p r i n t' xa n dya r ee q u a l ' e l s e : i fx<y : p r i n t' xi sl e s st h a ny ' e l s e : p r i n t' xi sg r e a t e rt h a ny '
en.wikibooks.org/wiki/Think_Python/Print_version
51/282
10/24/13
Recursion
Itislegalforonefunctiontocallanotheritisalsolegalforafunctiontocallitself.Itmaynotbeobviouswhythatisagoodthing,butitturnsouttobeoneof themostmagicalthingsaprogramcando.Forexample,lookatthefollowingfunction:
d e fc o u n t d o w n ( n ) : i fn< =0 : p r i n t' B l a s t o f f ! ' e l s e : p r i n tn c o u n t d o w n ( n 1 )
Theexecutionof c o u n t d o w n beginswith n = 0 ,andsince n isnotgreaterthan0,itoutputstheword,Blastoff!andthen returns. The c o u n t d o w n thatgot n = 1 returns. The c o u n t d o w n thatgot n = 2 returns. The c o u n t d o w n thatgot n = 3 returns. Andthenyourebackin _ _ m a i n _ _ .So,thetotaloutputlookslikethis:
3 2 1 B l a s t o f f !
en.wikibooks.org/wiki/Think_Python/Print_version 52/282
10/24/13
If n< =0 the r e t u r n statementexitsthefunction.Theflowofexecutionimmediatelyreturnstothecaller,andtheremaininglinesofthefunctionarenot executed. Therestofthefunctionissimilarto c o u n t d o w n :if n isgreaterthan0,itdisplays s andthencallsitselftodisplay s n1additionaltimes.Sothenumberoflinesof outputis 1+( n-1 ) ,whichaddsupto n . Forsimpleexampleslikethis,itisprobablyeasiertousea f o r loop.Butwewillseeexampleslaterthatarehardtowritewitha f o r loopandeasytowritewith recursion,soitisgoodtostartearly.
Stackdiagramsforrecursivefunctions
InSection3.10,weusedastackdiagramtorepresentthestateofaprogramduringafunctioncall.Thesamekindofdiagramcanhelpinterpretarecursive function. Everytimeafunctiongetscalled,Pythoncreatesanewfunctionframe,whichcontainsthefunctionslocalvariablesandparameters.Forarecursivefunction, theremightbemorethanoneframeonthestackatthesametime. Thisfigureshowsastackdiagramfor c o u n t d o w n calledwith n=3 : <IMGSRC="book007.png"> Asusual,thetopofthestackistheframefor _ _ m a i n _ _ .Itisemptybecausewedidnotcreateanyvariablesin _ _ m a i n _ _ orpassanyargumentstoit. Thefour c o u n t d o w n frameshavedifferentvaluesfortheparameter n .Thebottomofthestack,where n = 0 ,iscalledthe basecase.Itdoesnotmakearecursive call,sotherearenomoreframes. Drawastackdiagramfor p r i n t _ n calledwith s=' H e l l o ' and n = 2 . Writeafunctioncalled d o _ n thattakesafunctionobjectandanumber, n asarguments,andthatcallsthegivenfunction n times.
Infiniterecursion
Ifarecursionneverreachesabasecase,itgoesonmakingrecursivecallsforever,andtheprogramneverterminates.Thisisknownas infiniterecursion, anditisgenerallynotagoodidea.Hereisaminimalprogramwithaninfiniterecursion:
en.wikibooks.org/wiki/Think_Python/Print_version 53/282
10/24/13
d e fr e c u r s e ( ) : r e c u r s e ( )
Inmostprogrammingenvironments,aprogramwithinfiniterecursiondoesnotreallyrunforever.Pythonreportsanerrormessagewhenthemaximum recursiondepthisreached:
F i l e" < s t d i n > " ,l i n e2 ,i nr e c u r s e F i l e" < s t d i n > " ,l i n e2 ,i nr e c u r s e F i l e" < s t d i n > " ,l i n e2 ,i nr e c u r s e . . . F i l e" < s t d i n > " ,l i n e2 ,i nr e c u r s e R u n t i m e E r r o r :M a x i m u mr e c u r s i o nd e p t he x c e e d e d
Thistracebackisalittlebiggerthantheonewesawinthepreviouschapter.Whentheerroroccurs,thereare1000 r e c u r s e framesonthestack!
Keyboardinput
Theprogramswehavewrittensofarareabitrudeinthesensethattheyacceptnoinputfromtheuser.Theyjustdothesamethingeverytime. Pythonprovidesabuiltinfunctioncalled r a w _ i n p u t thatgetsinputfromthekeyboard[1].Whenthisfunctioniscalled,theprogramstopsandwaitsfortheuserto typesomething.WhentheuserpressesReturnorEnter,theprogramresumesand r a w _ i n p u t returnswhattheusertypedasastring.
> > >i n p u t=r a w _ i n p u t ( ) W h a ta r ey o uw a i t i n gf o r ? > > >p r i n ti n p u t W h a ta r ey o uw a i t i n gf o r ?
Beforegettinginputfromtheuser,itisagoodideatoprintaprompttellingtheuserwhattoinput. r a w _ i n p u t cantakeapromptasanargument:
> > >n a m e=r a w _ i n p u t ( ' W h a t . . . i sy o u rn a m e ? \ n ' ) W h a t . . . i sy o u rn a m e ? A r t h u r ,K i n go ft h eB r i t o n s ! > > >p r i n tn a m e A r t h u r ,K i n go ft h eB r i t o n s !
10/24/13
> > >p r o m p t=' W h a t . . . i st h ea i r s p e e dv e l o c i t yo fa nu n l a d e ns w a l l o w ? \ n ' > > >s p e e d=r a w _ i n p u t ( p r o m p t ) W h a t . . . i st h ea i r s p e e dv e l o c i t yo fa nu n l a d e ns w a l l o w ? 1 7 > > >i n t ( s p e e d ) 1 7
Butiftheusertypessomethingotherthanastringofdigits,yougetanerror:
> > >s p e e d=r a w _ i n p u t ( p r o m p t ) W h a t . . . i st h ea i r s p e e dv e l o c i t yo fa nu n l a d e ns w a l l o w ? W h a td oy o um e a n ,a nA f r i c a no raE u r o p e a ns w a l l o w ? > > >i n t ( s p e e d ) V a l u e E r r o r :i n v a l i dl i t e r a lf o ri n t ( )
Wewillseehowtohandlethiskindoferrorlater.
Debugging
ThetracebackPythondisplayswhenanerroroccurscontainsalotofinformation,butitcanbeoverwhelming,especiallywhentherearemanyframesonthe stack.Themostusefulpartsareusually: Whatkindoferroritwas,and Whereitoccurred. Syntaxerrorsareusuallyeasytofind,butthereareafewgotchas.Whitespaceerrorscanbetrickybecausespacesandtabsareinvisibleandweareusedto ignoringthem.
> > >x=5 > > > y=6 F i l e" < s t d i n > " ,l i n e1 y=6 ^ S y n t a x E r r o r :i n v a l i ds y n t a x
10/24/13
Butwhenyourunit,yougetanerrormessage:
T r a c e b a c k( m o s tr e c e n tc a l ll a s t ) : F i l e" s n r . p y " ,l i n e5 ,i n? d e c i b e l s=1 0*m a t h . l o g 1 0 ( r a t i o ) O v e r f l o w E r r o r :m a t hr a n g ee r r o r
Glossary
modulusoperator: Anoperator,denotedwithapercentsign(% ),thatworksonintegersandyieldstheremainderwhenonenumberisdividedbyanother. booleanexpression: Anexpressionwhosevalueiseither T r u e or F a l s e . comparisonoperator: Oneoftheoperatorsthatcomparesitsoperands: = = , ! = , > , < , > = ,and < = . logicaloperator: Oneoftheoperatorsthatcombinesbooleanexpressions: a n d , o r ,and n o t . conditionalstatement: Astatementthatcontrolstheflowofexecutiondependingonsomecondition. condition: Thebooleanexpressioninaconditionalstatementthatdetermineswhichbranchisexecuted. compoundstatement: Astatementthatconsistsofaheaderandabody.Theheaderendswithacolon(:).Thebodyisindentedrelativetotheheader. body: Thesequenceofstatementswithinacompoundstatement. branch: Oneofthealternativesequencesofstatementsinaconditionalstatement.
en.wikibooks.org/wiki/Think_Python/Print_version 56/282
10/24/13
chainedconditional: Aconditionalstatementwithaseriesofalternativebranches. nestedconditional: Aconditionalstatementthatappearsinoneofthebranchesofanotherconditionalstatement. recursion: Theprocessofcallingthefunctionthatiscurrentlyexecuting. basecase: Aconditionalbranchinarecursivefunctionthatdoesnotmakearecursivecall. infiniterecursion: Afunctionthatcallsitselfrecursivelywithouteverreachingthebasecase.Eventually,aninfiniterecursioncausesaruntimeerror.
Exercises
Exercise1 FermatsLastTheoremsaysthattherearenointegers'a','b',and'c'suchthat an+ bn= cn foranyvaluesof'n'greaterthan2. Writeafunctionnamed c h e c k _ f e r m a t thattakesfour parameters'a ','b ','c 'and'n 'andthatcheckstoseeifFermatstheoremholds.If 'n'isgreaterthan2anditturnsouttobetruethat 'a''n ' '+ b''n ' '= c''n ' '' 'theprogramshouldprint,Holysmokes,Fermatwaswrong!Otherwisetheprogramshouldprint,No,thatdoesntwork.' 'Writeafunctionthatpromptstheusertoinputvalues for'''a ''','''b ''','''c '''and'''n ''',convertsthemtointegers,anduses'' c h e c k _ f e r m a t ' 'tocheckwhethertheyviolateFermatstheorem.' Exercise2 Ifyouaregiventhreesticks,youmayormaynotbeabletoarrangetheminatriangle.Forexample,ifoneofthesticksis12incheslongandthe othertwoareoneinchlong,itisclearthatyouwillnotbeabletogettheshortstickstomeetinthemiddle.Foranythreelengths,thereisasimpletesttosee ifitispossibletoformatriangle: Ifanyofthethreelengthsisgreaterthanthesumoftheothertwo,thenyoucannotformatriangle.Otherwise,youcan[2]. Writeafunctionnamed i s _ t r i a n g l e thattakesthree
en.wikibooks.org/wiki/Think_Python/Print_version
57/282
10/24/13
Exercise4 TheKochcurveisafractalthatlookssomethinglikethis: <IMGSRC="book008.png"> TodrawaKochcurvewithlength'x',allyouhavetodois DrawaKochcurvewithlength'x/3'. Turnleft60degrees. DrawaKochcurvewithlength'x/3'. Turnright120degrees. DrawaKochcurvewithlength'x/3'. Turnleft60degrees. DrawaKochcurvewithlength'x/3'.
en.wikibooks.org/wiki/Think_Python/Print_version 58/282
10/24/13
Theonlyexceptionisif'x'islessthan3.Inthatcase, youcanjustdrawastraightlinewithlength'x'. Writeafunctioncalled'k o c h 'thattakesaturtleand alengthasparameters,andthatusestheturtletodrawaKochcurvewiththegivenlength. Writeafunctioncalled's n o w f l a k e 'thatdrawsthree Kochcurvestomaketheoutlineofasnowflake. Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / k o c h . p y '. TheKochcurvecanbegeneralizedinseveralways.See 'w i k i p e d i a . o r g / w i k i / K o c h _ s n o w f l a k e 'forexamplesandimplementyourfavorite.
Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.
Fruitfulfunctions
Returnvalues
Someofthebuiltinfunctionswehaveused,suchasthemathfunctions,produceresults.Callingthefunctiongeneratesavalue,whichweusuallyassigntoa variableoruseaspartofanexpression.
e=m a t h . e x p ( 1 . 0 ) h e i g h t=r a d i u s*m a t h . s i n ( r a d i a n s )
10/24/13
r e t u r nm a t h . p i*r a d i u s * * 2
Bytheway,Pythonprovidesabuiltinfunctioncalled a b s thatcomputesabsolutevalues.
Exercise1
Writea'c o m p a r e 'functionthatreturns'1 'if'x>y ','0 'if'x= =y ',and'1 'if'x<y '.
Incrementaldevelopment
Asyouwritelargerfunctions,youmightfindyourselfspendingmoretimedebugging.
en.wikibooks.org/wiki/Think_Python/Print_version
Todealwithincreasinglycomplexprograms,youmightwanttotryaprocesscalled incrementaldevelopment.Thegoalofincrementaldevelopmentisto
60/282
10/24/13
10/24/13
Again,youwouldruntheprogramatthisstageandchecktheoutput(whichshouldbe25).Finally,youcanuse m a t h . s q r t tocomputeandreturntheresult:
d e fd i s t a n c e ( x 1 ,y 1 ,x 2 ,y 2 ) : d x=x 2-x 1 d y=y 2-y 1 d s q u a r e d=d x * * 2+d y * * 2 r e s u l t=m a t h . s q r t ( d s q u a r e d ) r e t u r nr e s u l t
Ifthatworkscorrectly,youaredone.Otherwise,youmightwanttoprintthevalueof r e s u l t beforethereturnstatement. Thefinalversionofthefunctiondoesntdisplayanythingwhenitrunsitonlyreturnsavalue.The p r i n t statementswewroteareusefulfordebugging,butonce yougetthefunctionworking,youshouldremovethem.Codelikethatiscalled scaffoldingbecauseitishelpfulforbuildingtheprogrambutisnotpartofthe finalproduct. Whenyoustartout,youshouldaddonlyalineortwoofcodeatatime.Asyougainmoreexperience,youmightfindyourselfwritinganddebuggingbigger chunks.Eitherway,incrementaldevelopmentcansaveyoualotofdebuggingtime. Thekeyaspectsoftheprocessare: Startwithaworkingprogramandmakesmallincrementalchanges.Atanypoint,ifthereisanerror,youshouldhaveagoodideawhereitis. Usetemporaryvariablestoholdintermediatevaluessoyoucandisplayandcheckthem. Oncetheprogramisworking,youmightwanttoremovesomeofthescaffoldingorconsolidatemultiplestatementsintocompoundexpressions,but onlyifitdoesnotmaketheprogramdifficulttoread.
Exercise2
Useincrementaldevelopmenttowriteafunctioncalled'h y p o t e n u s e 'thatreturnsthelengthofthehypotenuseofarighttrianglegiventhelengthsofthetwolegs asarguments.Recordeachstageofthedevelopmentprocessasyougo.
Composition
Asyoushouldexpectbynow,youcancallonefunctionfromwithinanother.Thisabilityiscalled composition. Asanexample,wellwriteafunctionthattakestwopoints,thecenterofthecircleandapointontheperimeter,andcomputestheareaofthecircle. Assumethatthecenterpointisstoredinthevariables x c and y c ,andtheperimeterpointisin x p and y p .Thefirststepistofindtheradiusofthecircle,whichis en.wikibooks.org/wiki/Think_Python/Print_version 62/282
10/24/13
Thenextstepistofindtheareaofacirclewiththatradiuswejustwrotethat,too:
r e s u l t=a r e a ( r a d i u s )
Encapsulatingthesestepsinafunction,weget:
d e fc i r c l e _ a r e a ( x c ,y c ,x p ,y p ) : r a d i u s=d i s t a n c e ( x c ,y c ,x p ,y p ) r e s u l t=a r e a ( r a d i u s ) r e t u r nr e s u l t
Booleanfunctions
Functionscanreturnbooleans,whichisoftenconvenientforhidingcomplicatedtestsinsidefunctions.Forexample:
d e fi s _ d i v i s i b l e ( x ,y ) : i fx%y= =0 : r e t u r nT r u e e l s e : r e t u r nF a l s e
10/24/13
Theresultofthe = = operatorisaboolean,sowecanwritethefunctionmoreconciselybyreturningitdirectly:
d e fi s _ d i v i s i b l e ( x ,y ) : r e t u r nx%y= =0
Booleanfunctionsareoftenusedinconditionalstatements:
i fi s _ d i v i s i b l e ( x ,y ) : p r i n t' xi sd i v i s i b l eb yy '
Itmightbetemptingtowritesomethinglike:
i fi s _ d i v i s i b l e ( x ,y )= =T r u e : p r i n t' xi sd i v i s i b l eb yy '
Morerecursion
WehaveonlycoveredasmallsubsetofPython,butyoumightbeinterestedtoknowthatthissubsetisa completeprogramminglanguage,whichmeansthat anythingthatcanbecomputedcanbeexpressedinthislanguage.Anyprogrameverwrittencouldberewrittenusingonlythelanguagefeaturesyouhave learnedsofar(actually,youwouldneedafewcommandstocontroldeviceslikethekeyboard,mouse,disks,etc.,butthatsall). ProvingthatclaimisanontrivialexercisefirstaccomplishedbyAlanTuring,oneofthefirstcomputerscientists(somewouldarguethathewasa mathematician,butalotofearlycomputerscientistsstartedasmathematicians).Accordingly,itisknownastheTuringThesis.Foramorecomplete(and accurate)discussionoftheTuringThesis,IrecommendMichaelSipsersbook IntroductiontotheTheoryofComputation. Togiveyouanideaofwhatyoucandowiththetoolsyouhavelearnedsofar,wellevaluateafewrecursivelydefinedmathematicalfunctions.Arecursive definitionissimilartoacirculardefinition,inthesensethatthedefinitioncontainsareferencetothethingbeingdefined.Atrulycirculardefinitionisnotvery useful: frabjuous: Anadjectiveusedtodescribesomethingthatisfrabjuous. Ifyousawthatdefinitioninthedictionary,youmightbeannoyed.Ontheotherhand,ifyoulookedupthedefinitionofthefactorialfunction,denotedwiththe symbol!,youmightgetsomethinglikethis:
en.wikibooks.org/wiki/Think_Python/Print_version 64/282
10/24/13
0!=1 n!= n(n1)! Thisdefinitionsaysthatthefactorialof0is1,andthefactorialofanyothervalue, n,is nmultipliedbythefactorialof n1. So3!is3times2!,whichis2times1!,whichis1times0!.Puttingitalltogether,3!equals3times2times1times1,whichis6. Ifyoucanwritearecursivedefinitionofsomething,youcanusuallywriteaPythonprogramtoevaluateit.Thefirststepistodecidewhattheparameters shouldbe.Inthiscaseitshouldbeclearthat f a c t o r i a l takesaninteger:
d e ff a c t o r i a l ( n ) :
Iftheargumenthappenstobe0,allwehavetodoisreturn1:
d e ff a c t o r i a l ( n ) : i fn= =0 : r e t u r n1
Otherwise,andthisistheinterestingpart,wehavetomakearecursivecalltofindthefactorialof n1andthenmultiplyitby n:
d e ff a c t o r i a l ( n ) : i fn= =0 : r e t u r n1 e l s e : r e c u r s e=f a c t o r i a l ( n 1 ) r e s u l t=n*r e c u r s e r e t u r nr e s u l t
10/24/13
<IMGSRC="book009.png">
Leapoffaith
Followingtheflowofexecutionisonewaytoreadprograms,butitcanquicklybecomelabyrinthine.AnalternativeiswhatIcalltheleapoffaith.Whenyou cometoafunctioncall,insteadoffollowingtheflowofexecution,you assumethatthefunctionworkscorrectlyandreturnstherightresult. Infact,youarealreadypracticingthisleapoffaithwhenyouusebuiltinfunctions.Whenyoucall m a t h . c o s or m a t h . e x p ,youdontexaminethebodiesofthose functions.Youjustassumethattheyworkbecausethepeoplewhowrotethebuiltinfunctionsweregoodprogrammers. Thesameistruewhenyoucalloneofyourownfunctions.Forexample,inSection6.4,wewroteafunctioncalled i s _ d i v i s i b l e thatdetermineswhetherone numberisdivisiblebyanother.Oncewehaveconvincedourselvesthatthisfunctioniscorrectbyexaminingthecodeandtestingwecanusethefunction withoutlookingatthebodyagain. Thesameistrueofrecursiveprograms.Whenyougettotherecursivecall,insteadoffollowingtheflowofexecution,youshouldassumethattherecursive callworks(yieldsthecorrectresult)andthenaskyourself,AssumingthatIcanfindthefactorialof n1,canIcomputethefactorialof n?Inthiscase,itis clearthatyoucan,bymultiplyingby n. Ofcourse,it'sabitstrangetoassumethatthefunctionworkscorrectlywhenyouhaven'tfinishedwritingit,butthat'swhyit'scalledaleapoffaith!
Onemoreexample
After f a c t o r i a l ,themostcommonexampleofarecursivelydefinedmathematicalfunctionis f i b o n a c c i ,whichhasthefollowingdefinition[3]: fibonacci(0)=0
en.wikibooks.org/wiki/Think_Python/Print_version 66/282
10/24/13
Checkingtypes
Whathappensifwecall f a c t o r i a l andgiveit1.5asanargument?
> > >f a c t o r i a l ( 1 . 5 ) R u n t i m e E r r o r :M a x i m u mr e c u r s i o nd e p t he x c e e d e d
Itlookslikeaninfiniterecursion.Buthowcanthatbe?Thereisabasecasewhen n= =0 .Butif n isnotaninteger,wecan missthebasecaseandrecurse forever. Inthefirstrecursivecall,thevalueof n is0.5.Inthenext,itis0.5.Fromthere,itgetssmaller(morenegative),butitwillneverbe0. Wehavetwochoices.Wecantrytogeneralizethe f a c t o r i a l functiontoworkwithfloatingpointnumbers,orwecanmake f a c t o r i a l checkthetypeofits argument.Thefirstoptioniscalledthegammafunction[4]anditsalittlebeyondthescopeofthisbook.Sowellgoforthesecond. Wecanusethebuiltinfunction i s i n s t a n c e toverifythetypeoftheargument.Whilewereatit,wecanalsomakesuretheargumentispositive:
10/24/13
e l i fn= =0 : r e t u r n1 e l s e : r e t u r nn*f a c t o r i a l ( n 1 )
Debugging
Breakingalargeprogramintosmallerfunctionscreatesnaturalcheckpointsfordebugging.Ifafunctionisnotworking,therearethreepossibilitiestoconsider: Thereissomethingwrongwiththeargumentsthefunction isgettingapreconditionisviolated. Thereissomethingwrongwiththefunctionapostcondition isviolated. Thereissomethingwrongwiththereturnvalueorthe wayitisbeingused. Toruleoutthefirstpossibility,youcanadda p r i n t statementatthebeginningofthefunctionanddisplaythevaluesoftheparameters(andmaybetheir types).Oryoucanwritecodethatchecksthepreconditionsexplicitly. Iftheparameterslookgood,adda p r i n t statementbeforeeach r e t u r n statementthatdisplaysthereturnvalue.Ifpossible,checktheresultbyhand.Consider callingthefunctionwithvaluesthatmakeiteasytochecktheresult(asinSection6.2). Ifthefunctionseemstobeworking,lookatthefunctioncalltomakesurethereturnvalueisbeingusedcorrectly(orusedatall!). Addingprintstatementsatthebeginningandendofafunctioncanhelpmaketheflowofexecutionmorevisible.Forexample,hereisaversionof f a c t o r i a l68/282 en.wikibooks.org/wiki/Think_Python/Print_version
10/24/13
Addingprintstatementsatthebeginningandendofafunctioncanhelpmaketheflowofexecutionmorevisible.Forexample,hereisaversionof f a c t o r i a l withprintstatements:
d e ff a c t o r i a l ( n ) : s p a c e=''*( 4*n ) p r i n ts p a c e ,' f a c t o r i a l ' ,n i fn= =0 : p r i n ts p a c e ,' r e t u r n i n g1 ' r e t u r n1 e l s e : r e c u r s e=f a c t o r i a l ( n 1 ) r e s u l t=n*r e c u r s e p r i n ts p a c e ,' r e t u r n i n g ' ,r e s u l t r e t u r nr e s u l t
s p a c e isastringofspacecharactersthatcontrolstheindentationoftheoutput.Hereistheresultof f a c t o r i a l ( 5 ) :
f a c t o r i a l5 f a c t o r i a l4 f a c t o r i a l3 f a c t o r i a l2 f a c t o r i a l1 f a c t o r i a l0 r e t u r n i n g1 r e t u r n i n g1 r e t u r n i n g2 r e t u r n i n g6 r e t u r n i n g2 4 r e t u r n i n g1 2 0
Ifyouareconfusedabouttheflowofexecution,thiskindofoutputcanbehelpful.Ittakessometimetodevelopeffectivescaffolding,butalittlebitof scaffoldingcansavealotofdebugging.
Glossary
temporaryvariable: Avariableusedtostoreanintermediatevalueinacomplexcalculation. deadcode: Partofaprogramthatcanneverbeexecuted,oftenbecauseitappearsaftera r e t u r n statement. 'N o n e ': Aspecialvaluereturnedbyfunctionsthathavenoreturnstatementorareturnstatementwithoutanargument. incrementaldevelopment: Aprogramdevelopmentplanintendedtoavoiddebuggingbyaddingandtestingonlyasmallamountofcodeatatime.
en.wikibooks.org/wiki/Think_Python/Print_version 69/282
10/24/13
Exercises
Exercise4
Drawastackdiagramforthefollowingprogram.Whatdoestheprogramprint?
d e fb ( z ) : p r o d=a ( z ,z ) p r i n tz ,p r o d r e t u r np r o d d e fa ( x ,y ) : x=x+1 r e t u r nx*y d e fc ( x ,y ,z ) : s u m=x+y+z p o w=b ( s u m ) * * 2 r e t u r np o w x=1 y=x+1 p r i n tc ( x ,y + 3 ,x + y )
Exercise5
TheAckermannfunction,'A(m,n)'isdefined[5]:
1 See w i k i p e d i a . o r g / w i k i / C o l l a t z _ c o n j e c t u r e . 2 See w i k i p e d i a . o r g / w i k i / P i .
Strings
en.wikibooks.org/wiki/Think_Python/Print_version 70/282
10/24/13
Astringisasequence
Astringisa sequenceofcharacters.Youcanaccessthecharactersoneatatimewiththebracketoperator:
> > >f r u i t=' b a n a n a ' > > >l e t t e r=f r u i t [ 1 ]
l e n
l e n isabuiltinfunctionthatreturnsthenumberofcharactersinastring:
Togetthelastletterofastring,youmightbetemptedtotrysomethinglikethis:
en.wikibooks.org/wiki/Think_Python/Print_version 71/282
10/24/13
Traversalwithaf o r loop
Alotofcomputationsinvolveprocessingastringonecharacteratatime.Oftentheystartatthebeginning,selecteachcharacterinturn,dosomethingtoit, andcontinueuntiltheend.Thispatternofprocessingiscalleda traversal .Onewaytowriteatraversaliswitha w h i l e loop:
i n d e x=0 w h i l ei n d e x<l e n ( f r u i t ) : l e t t e r=f r u i t [ i n d e x ] p r i n tl e t t e r i n d e x=i n d e x+1
Thislooptraversesthestringanddisplayseachletteronalinebyitself.Theloopconditionis i n d e x<l e n ( f r u i t ) ,sowhen i n d e x isequaltothelengthofthe string,theconditionisfalse,andthebodyoftheloopisnotexecuted.Thelastcharacteraccessedistheonewiththeindex l e n ( f r u i t ) 1 ,whichisthelast characterinthestring. Exercise1 Writeafunctionthattakesastringasanargumentanddisplaysthelettersbackward,oneperline. Anotherwaytowriteatraversaliswitha f o r loop:
f o rc h a ri nf r u i t : p r i n tc h a r
Eachtimethroughtheloop,thenextcharacterinthestringisassignedtothevariable c h a r .Theloopcontinuesuntilnocharactersareleft.
en.wikibooks.org/wiki/Think_Python/Print_version 72/282
10/24/13
Theoutputis:
J a c k K a c k L a c k M a c k N a c k O a c k P a c k Q a c k
Ofcourse,thatsnotquiterightbecauseOuackandQuackaremisspelled.
Exercise2
Modifytheprogramtofixthiserror.
Stringslices
Asegmentofastringiscalleda slice.Selectingasliceissimilartoselectingacharacter:
> > >s=' M o n t yP y t h o n ' > > >p r i n ts [ 0 : 5 ] M o n t y > > >p r i n ts [ 6 : 1 3 ] P y t h o n
10/24/13
> > >f r u i t=' b a n a n a ' > > >f r u i t [ : 3 ] ' b a n ' > > >f r u i t [ 3 : ] ' a n a '
Ifthefirstindexisgreaterthanorequaltothesecondtheresultisan emptystring,representedbytwoquotationmarks:
> > >f r u i t=' b a n a n a ' > > >f r u i t [ 3 : 3 ] ' '
Anemptystringcontainsnocharactersandhaslength0,butotherthanthat,itisthesameasanyotherstring.
Exercise3
Giventhat'f r u i t 'isastring,whatdoes'f r u i t [ : ] 'mean?
Stringsareimmutable
Itistemptingtousethe [ ] operatorontheleftsideofanassignment,withtheintentionofchangingacharacterinastring.Forexample:
> > >g r e e t i n g=' H e l l o ,w o r l d ! ' > > >g r e e t i n g [ 0 ]=' J ' T y p e E r r o r :o b j e c td o e sn o ts u p p o r ti t e ma s s i g n m e n t
Thisexampleconcatenatesanewfirstletterontoasliceof g r e e t i n g .Ithasnoeffectontheoriginalstring.
Searching
en.wikibooks.org/wiki/Think_Python/Print_version 74/282
10/24/13
Whatdoesthefollowingfunctiondo?
d e ff i n d ( w o r d ,l e t t e r ) : i n d e x=0 w h i l ei n d e x<l e n ( w o r d ) : i fw o r d [ i n d e x ]= =l e t t e r : r e t u r ni n d e x i n d e x=i n d e x+1 r e t u r n1
Inasense, f i n d istheoppositeofthe [ ] operator.Insteadoftakinganindexandextractingthecorrespondingcharacter,ittakesacharacterandfindsthe indexwherethatcharacterappears.Ifthecharacterisnotfound,thefunctionreturns 1 . Thisisthefirstexamplewehaveseenofa r e t u r n statementinsidealoop.If w o r d [ i n d e x ]= =l e t t e r ,thefunctionbreaksoutoftheloopandreturnsimmediately. Ifthecharacterdoesntappearinthestring,theprogramexitstheloopnormallyandreturns 1 . Thispatternofcomputationtraversingasequenceandreturningwhenwefindwhatwearelookingforisacalleda search.
Exercise4
Modify'f i n d 'sothatithasathirdparameter,theindexin'w o r d 'whereitshouldstartlooking.
Loopingandcounting
Thefollowingprogramcountsthenumberoftimestheletter a appearsinastring:
w o r d=' b a n a n a ' c o u n t=0 f o rl e t t e ri nw o r d : i fl e t t e r= =' a ' : c o u n t=c o u n t+1 p r i n tc o u n t
en.wikibooks.org/wiki/Think_Python/Print_version
75/282
10/24/13
Rewritethisfunctionsothatinsteadoftraversingthestring,itusesthethreeparameterversionof'f i n d 'fromtheprevioussection.
s t r i n g methods
A methodissimilartoafunctionittakesargumentsandreturnsavaluebutthesyntaxisdifferent.Forexample,themethod u p p e r takesastringand returnsanewstringwithalluppercaseletters: Insteadofthefunctionsyntax u p p e r ( w o r d ) ,itusesthemethodsyntax w o r d . u p p e r ( ) .
> > >w o r d=' b a n a n a ' > > >n e w _ w o r d=w o r d . u p p e r ( ) > > >p r i n tn e w _ w o r d B A N A N A
Itcantakeasasecondargumenttheindexwhereitshouldstart:
10/24/13
Andasathirdargumenttheindexwhereitshouldstop:
> > >n a m e=' b o b ' > > >n a m e . f i n d ( ' b ' ,1 ,2 ) 1
Thei n operator
Theword i n isabooleanoperatorthattakestwostringsandreturns T r u e ifthefirstappearsasasubstringinthesecond:
> > >' a 'i n' b a n a n a ' T r u e > > >' s e e d 'i n' b a n a n a ' F a l s e
Forexample,thefollowingfunctionprintsallthelettersfrom w o r d 1 thatalsoappearin w o r d 2 :
d e fi n _ b o t h ( w o r d 1 ,w o r d 2 ) : f o rl e t t e ri nw o r d 1 : i fl e t t e ri nw o r d 2 : p r i n tl e t t e r
10/24/13
Stringcomparison
Thecomparisonoperatorsworkonstrings.Toseeiftwostringsareequal:
i fw o r d= =' b a n a n a ' : p r i n t ' A l lr i g h t ,b a n a n a s . '
Othercomparisonoperationsareusefulforputtingwordsinalphabeticalorder:
i fw o r d<' b a n a n a ' : p r i n t' Y o u rw o r d , '+w o r d+' ,c o m e sb e f o r eb a n a n a . ' e l i fw o r d>' b a n a n a ' : p r i n t' Y o u rw o r d , '+w o r d+' ,c o m e sa f t e rb a n a n a . ' e l s e : p r i n t' A l lr i g h t ,b a n a n a s . '
Pythondoesnothandleuppercaseandlowercaselettersthesamewaythatpeopledo.Alltheuppercaseletterscomebeforeallthelowercaseletters,so:
Y o u rw o r d ,P i n e a p p l e ,c o m e sb e f o r eb a n a n a .
Acommonwaytoaddressthisproblemistoconvertstringstoastandardformat,suchasalllowercase,beforeperformingthecomparison.Keepthatinmind incaseyouhavetodefendyourselfagainstamanarmedwithaPineapple.
Debugging
Whenyouuseindicestotraversethevaluesinasequence,itistrickytogetthebeginningandendofthetraversalright.Hereisafunctionthatissupposedto comparetwowordsandreturn T r u e ifoneofthewordsisthereverseoftheother,butitcontainstwoerrors:
d e fi s _ r e v e r s e ( w o r d 1 ,w o r d 2 ) : i fl e n ( w o r d 1 )! =l e n ( w o r d 2 ) : r e t u r nF a l s e i=0 j=l e n ( w o r d 2 ) w h i l ej>0 : i fw o r d 1 [ i ]! =w o r d 2 [ j ] : r e t u r nF a l s e i=i + 1 j=j 1
en.wikibooks.org/wiki/Think_Python/Print_version 78/282
10/24/13
r e t u r nT r u e
Fordebuggingthiskindoferror,myfirstmoveistoprintthevaluesoftheindicesimmediatelybeforethelinewheretheerrorappears.
w h i l ej>0 : p r i n ti ,j
#p r i n th e r e
i fw o r d 1 [ i ]! =w o r d 2 [ j ] : r e t u r nF a l s e i=i + 1 j=j 1
NowwhenIruntheprogramagain,Igetmoreinformation:
> > >i s _ r e v e r s e ( ' p o t s ' ,' s t o p ' ) 04 . . . I n d e x E r r o r :s t r i n gi n d e xo u to fr a n g e
IfIfixthaterrorandruntheprogramagain,Iget:
en.wikibooks.org/wiki/Think_Python/Print_version 79/282
10/24/13
Glossary
object: Somethingavariablecanreferto.Fornow,youcanuseobjectandvalueinterchangeably. sequence: Anorderedsetthatis,asetofvalueswhereeachvalueisidentifiedbyanintegerindex. item: Oneofthevaluesinasequence. index: Anintegervalueusedtoselectaniteminasequence,suchasacharacterinastring. slice: Apartofastringspecifiedbyarangeofindices. emptystring: Astringwithnocharactersandlength0,representedbytwoquotationmarks. immutable: Thepropertyofasequencewhoseitemscannotbeassigned. traverse: Toiteratethroughtheitemsinasequence,performingasimilaroperationoneach. search: Apatternoftraversalthatstopswhenitfindswhatitislookingfor.
en.wikibooks.org/wiki/Think_Python/Print_version 80/282
10/24/13
Exercises
Exercise9
Astringslicecantakeathirdindexthatspecifiesthestepsizethatis,thenumberofspacesbetweensuccessivecharacters.Astepsizeof2meansevery othercharacter3meanseverythird,etc.
' ' > > >f r u i t=' b a n a n a ' > > >f r u i t [ 0 : 5 : 2 ] ' b n n ' ' '
Exercise10
Readthedocumentationofthestringmethodsat'd o c s . p y t h o n . o r g / l i b / s t r i n g m e t h o d s . h t m l '.Youmightwanttoexperimentwithsomeofthemtomakesureyou understandhowtheywork.'s t r i p 'and'r e p l a c e 'areparticularlyuseful. Thedocumentationusesasyntaxthatmightbeconfusing. Forexample,in f i n d ( s u b [ ,s t a r t [ ,e n d ] ] ) ,thebracketsindicateoptionalarguments.So's u b 'is required,but's t a r t 'isoptional,andifyouinclude's t a r t ',then'e n d 'isoptional.
Exercise11
Thefollowingfunctionsareall intendedtocheckwhetherastringcontainsanylowercaseletters,butatleastsomeofthemare wrong.Foreachfunction,describewhatthefunctionactuallydoes.
' ' d e fa n y _ l o w e r c a s e 1 ( s ) : f o rci ns : i fc . i s l o w e r ( ) : r e t u r nT r u e
en.wikibooks.org/wiki/Think_Python/Print_version 81/282
10/24/13
e l s e : r e t u r nF a l s e d e fa n y _ l o w e r c a s e 2 ( s ) : f o rci ns : i f' c ' . i s l o w e r ( ) : r e t u r n' T r u e ' e l s e : r e t u r n' F a l s e ' d e fa n y _ l o w e r c a s e 3 ( s ) : f o rci ns : f l a g=c . i s l o w e r ( ) r e t u r nf l a g d e fa n y _ l o w e r c a s e 4 ( s ) : f l a g=F a l s e f o rci ns : f l a g=f l a go rc . i s l o w e r ( ) r e t u r nf l a g d e fa n y _ l o w e r c a s e 5 ( s ) : f o rci ns : i fn o tc . i s l o w e r ( ) : r e t u r nF a l s e r e t u r nT r u e ' '
Exercise12
ROT13isaweakformofencryptionthatinvolvesrotatingeachletterinawordby13places[7].Torotatealettermeanstoshiftitthroughthealphabet, wrappingaroundtothebeginningifnecessary,soAshiftedby3isDandZshiftedby1isA. Writeafunctioncalled r o t a t e _ w o r d thattakesastringandanintegerasparameters,andthatreturnsanewstringthatcontainsthelettersfromtheoriginal stringrotatedbythegivenamount. Forexample,cheerrotatedby7isjollyandmelonrotatedby10iscubed. Youmightwanttousethebuiltinfunctions'o r d ',whichconvertsacharactertoanumericcode,and'c h r ',whichconvertsnumericcodestocharacters. PotentiallyoffensivejokesontheInternetaresometimesencodedinROT13.Ifyouarenoteasilyoffended,findanddecodesomeofthem.
Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.
en.wikibooks.org/wiki/Think_Python/Print_version 82/282
10/24/13
Casestudy:wordplay
Readingwordlists
FortheexercisesinthischapterweneedalistofEnglishwords.TherearelotsofwordlistsavailableontheWeb,buttheonemostsuitableforourpurposeis oneofthewordlistscollectedandcontributedtothepublicdomainbyGradyWardaspartoftheMobylexiconproject [8].Itisalistof113,809official crosswordsthatis,wordsthatareconsideredvalidincrosswordpuzzlesandotherwordgames.IntheMobycollection,thefilenameis 1 1 3 8 0 9 o f . f i c Iincludea copyofthisfile,withthesimplername w o r d s . t x t ,alongwithSwampy. Thisfileisinplaintext,soyoucanopenitwithatexteditor,butyoucanalsoreaditfromPython.(Youmayneedtomovethefilefromtheswampyfolder intothemainpythonfolder)Thebuiltinfunction o p e n takesthenameofthefileasaparameterandreturnsa fileobjectyoucanusetoreadthefile.
> > >f i n=o p e n ( ' w o r d s . t x t ' ) > > >p r i n tf i n < o p e nf i l e' w o r d s . t x t ' ,m o d e' r 'a t0 x b 7 f 4 b 3 8 0 >
f i n isacommonnameforafileobjectusedforinput.Mode ' r ' indicatesthatthisfileisopenforreading(asopposedto ' w ' forwriting).
Thenextwordisaah,whichisaperfectlylegitimateword,sostoplookingatmelikethat.Or,ifitsthewhitespacethatsbotheringyou,wecangetridofit withthestringmethod s t r i p :
> > >l i n e=f i n . r e a d l i n e ( ) > > >w o r d=l i n e . s t r i p ( ) > > >p r i n tw o r d a a h e d
en.wikibooks.org/wiki/Think_Python/Print_version
83/282
10/24/13
Exercises
Therearesolutionstotheseexercisesinthenextsection.Youshouldatleastattempteachonebeforeyoureadthesolutions. Exercise2 In1939ErnestVincentWrightpublisheda50,000wordnovelcalled Gadsbythatdoesnotcontainthelettere.Sinceeisthemostcommonletterin English,thatsnoteasytodo. Infact,itisdifficulttoconstructasolitarythoughtwithoutusingthatmostcommonsymbol.Itisslowgoingatfirst,butwith cautionandhoursoftrainingyoucangraduallygainfacility. Allright,Illstopnow. Writeafunctioncalled h a s _ n o _ e thatreturns'T r u e 'if thegivenworddoesnthavethelettereinit. Modifyyourprogramfromtheprevioussectiontoprintonlythewordsthathavenoeandcomputethepercentageofthewordsinthelisthavenoe. Exercise3 Writeafunctionnamed'a v o i d s 'thattakesawordandastringofforbiddenletters,andthatreturns'T r u e 'iftheworddoesntuseanyoftheforbiddenletters. Modifyyourprogramtoprompttheusertoenterastringofforbiddenlettersandthenprintthenumberofwordsthatdontcontainanyofthem.Canyoufinda combinationof5forbiddenlettersthatexcludesthesmallestnumberofwords? Exercise4 Writeafunctionnamed u s e s _ o n l y thattakesawordandastringofletters,andthatreturns'T r u e 'ifthewordcontainsonlylettersinthelist.Canyoumakea sentenceusingonlytheletters'a c e f h l o '?OtherthanHoealfalfa? Exercise5 Writeafunctionnamed u s e s _ a l l thattakesawordandastringofrequiredletters,andthatreturns'T r u e 'ifthewordusesalltherequiredlettersatleastonce. Howmanywordsaretherethatuseallthevowels'a e i o u '?Howabout'a e i o u y '? Exercise6
en.wikibooks.org/wiki/Think_Python/Print_version 84/282
10/24/13
Search
AlloftheexercisesintheprevioussectionhavesomethingincommontheycanbesolvedwiththesearchpatternwesawinSection8.6.Thesimplest exampleis:
d e fh a s _ n o _ e ( w o r d ) : f o rl e t t e ri nw o r d : i fl e t t e r= =' e ' : r e t u r nF a l s e r e t u r nT r u e
d e fa v o i d s ( w o r d ,f o r b i d d e n ) : f o rl e t t e ri nw o r d : i fl e t t e ri nf o r b i d d e n : r e t u r nF a l s e r e t u r nT r u e
Wecanreturn F a l s e assoonaswefindaforbiddenletterifwegettotheendoftheloop,wereturn T r u e .
u s e s _ o n l y issimilarexceptthatthesenseoftheconditionisreversed:
d e fu s e s _ o n l y ( w o r d ,a v a i l a b l e ) : f o rl e t t e ri nw o r d : i fl e t t e rn o ti na v a i l a b l e : r e t u r nF a l s e r e t u r nT r u e
en.wikibooks.org/wiki/Think_Python/Print_version
85/282
10/24/13
u s e s _ a l l issimilarexceptthatwereversetheroleofthewordandthestringofletters:
d e fu s e s _ a l l ( w o r d ,r e q u i r e d ) : f o rl e t t e ri nr e q u i r e d : i fl e t t e rn o ti nw o r d : r e t u r nF a l s e r e t u r nT r u e
Loopingwithindices
Iwrotethefunctionsintheprevioussectionwith f o r loopsbecauseIonlyneededthecharactersinthestringsIdidnthavetodoanythingwiththeindices. For i s _ a b e c e d a r i a n wehavetocompareadjacentletters,whichisalittletrickywitha f o r loop:
d e fi s _ a b e c e d a r i a n ( w o r d ) : p r e v i o u s=w o r d [ 0 ] f o rci nw o r d : i fc<p r e v i o u s : r e t u r nF a l s e p r e v i o u s=c r e t u r nT r u e
Analternativeistouserecursion:
d e fi s _ a b e c e d a r i a n ( w o r d ) : i fl e n ( w o r d )< =1 : r e t u r nT r u e i fw o r d [ 0 ]>w o r d [ 1 ] :
en.wikibooks.org/wiki/Think_Python/Print_version 86/282
10/24/13
r e t u r nF a l s e r e t u r ni s _ a b e c e d a r i a n ( w o r d [ 1 : ] )
Anotheroptionistousea w h i l e loop:
d e fi s _ a b e c e d a r i a n ( w o r d ) : i=0 w h i l ei<l e n ( w o r d ) 1 : i fw o r d [ i + 1 ]<w o r d [ i ] : r e t u r nF a l s e i=i + 1 r e t u r nT r u e
Theloopstartsat i = 0 andendswhen i = l e n ( w o r d ) 1 .Eachtimethroughtheloop,itcomparestheithcharacter(whichyoucanthinkofasthecurrentcharacter)to thei+1thcharacter(whichyoucanthinkofasthenext). Ifthenextcharacterislessthan(alphabeticallybefore)thecurrentone,thenwehavediscoveredabreakintheabecedariantrend,andwereturn F a l s e . Ifwegettotheendoftheloopwithoutfindingafault,thenthewordpassesthetest.Toconvinceyourselfthattheloopendscorrectly,consideranexample like ' f l o s s y ' .Thelengthofthewordis6,sothelasttimethelooprunsiswhen i is4,whichistheindexofthesecondtolastcharacter.Onthelastiteration,it comparesthesecondtolastcharactertothelast,whichiswhatwewant. Hereisaversionof i s _ p a l i n d r o m e (seeExercise6.6)thatusestwoindicesonestartsatthebeginningandgoesuptheotherstartsattheendandgoesdown.
d e fi s _ p a l i n d r o m e ( w o r d ) : i=0 j=l e n ( w o r d ) 1 w h i l ei < j : i fw o r d [ i ]! =w o r d [ j ] : r e t u r nF a l s e i=i + 1 j=j 1 r e t u r nT r u e
Or,ifyounoticedthatthisisaninstanceofapreviouslysolvedproblem,youmighthavewritten:
d e fi s _ p a l i n d r o m e ( w o r d ) : r e t u r ni s _ r e v e r s e ( w o r d ,w o r d )
en.wikibooks.org/wiki/Think_Python/Print_version
87/282
10/24/13
AssumingyoudidExercise8.8.
Debugging
Testingprogramsishard.Thefunctionsinthischapterarerelativelyeasytotestbecauseyoucanchecktheresultsbyhand.Evenso,itissomewhere betweendifficultandimpossibletochooseasetofwordsthattestforallpossibleerrors. Taking h a s _ n o _ e asanexample,therearetwoobviouscasestocheck:wordsthathaveaneshouldreturn F a l s e wordsthatdontshouldreturn T r u e .Youshould havenotroublecomingupwithoneofeach. Withineachcase,therearesomelessobvioussubcases.Amongthewordsthathaveane,youshouldtestwordswithaneatthebeginning,theend,and somewhereinthemiddle.Youshouldtestlongwords,shortwords,andveryshortwords,liketheemptystring.Theemptystringisanexampleofa special case,whichisoneofthenonobviouscaseswhereerrorsoftenlurk. Inadditiontothetestcasesyougenerate,youcanalsotestyourprogramwithawordlistlike w o r d s . t x t .Byscanningtheoutput,youmightbeabletocatch errors,butbecareful:youmightcatchonekindoferror(wordsthatshouldnotbeincluded,butare)andnotanother(wordsthatshouldbeincluded,but arent). Ingeneral,testingcanhelpyoufindbugs,butitisnoteasytogenerateagoodsetoftestcases,andevenifyoudo,youcantbesureyourprogramiscorrect. Accordingtoalegendarycomputerscientist: Programtestingcanbeusedtoshowthepresenceofbugs,butnevertoshowtheirabsence!EdsgerW.Dijkstra
Glossary
fileobject: Avaluethatrepresentsanopenfile. problemrecognition: Awayofsolvingaproblembyexpressingitasaninstanceofapreviouslysolvedproblem. specialcase: Atestcasethatisatypicalornonobvious(andlesslikelytobehandledcorrectly).
Exercises
Exercise7
ThisquestionisbasedonaPuzzlerthatwasbroadcastontheradioprogram CarTalk[9]: Givemeawordwiththreeconsecutivedoubleletters.I'llgiveyoua
coupleofwordsthatalmostqualify,butdon't.Forexample,thewordcommittee,committee.Itwouldbegreatexceptfortheithatsneaks en.wikibooks.org/wiki/Think_Python/Print_version
88/282
10/24/13
Exercise8
Heresanother CarTalkPuzzler[10]: IwasdrivingonthehighwaytheotherdayandIhappenedtonoticemyodometer.Likemostodometers,itshowssixdigits,inwholemilesonly. So,ifmycarhad300,000miles,forexample,Idsee300000. Now,whatIsawthatdaywasveryinteresting.Inoticedthatthelast4digits werepalindromicthatis,theyreadthesameforwardasbackward.Forexample,5445isapalindrome,somyodometercouldhaveread31 5445. Onemilelater,thelast5numberswerepalindromic.Forexample,it couldhaveread365456.Onemileafterthat,themiddle4outof6 numberswerepalindromic.Andyoureadyforthis?Onemilelater,all6werepalindromic! Thequestionis,whatwasontheodometerwhenIfirstlooked? WriteaPythonprogramthattestsallthesixdigitnumbersandprintsanynumbersthatsatisfytheserequirements.Youcanseemysolutionat 't h i n k p y t h o n . c o m / c o d e / c a r t a l k . p y '.
Exercise9
Heresanother CarTalkPuzzleryoucansolvewithasearch[11]: RecentlyIhadavisitwithmymomandwerealizedthatthetwodigitsthatmakeupmyagewhenreversedresultedinherage.Forexample,if shes73,Im37.Wewonderedhowoftenthishashappenedovertheyearsbutwegotsidetrackedwithothertopicsandwenevercameupwith ananswer. WhenIgothomeIfiguredoutthatthedigitsofourageshavebeenreversiblesixtimessofar.Ialsofiguredoutthatifwereluckyit wouldhappenagaininafewyears,andifwerereallyluckyitwouldhappenonemoretimeafterthat.Inotherwords,itwouldhavehappened8 timesoverall.Sothequestionis,howoldamInow? WriteaPythonprogramthatsearchesforsolutionstothisPuzzler. Hint:youmightfindthestringmethod'z f i l l 'useful. Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / c a r t a l k . p y '.
Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.
Lists
en.wikibooks.org/wiki/Think_Python/Print_version 89/282
10/24/13
Alistisasequence
Likeastring,a listisasequenceofvalues.Inastring,thevaluesarecharactersinalist,theycanbeanytype.Thevaluesinlistarecalled elementsor sometimes items. Thereareseveralwaystocreateanewlistthesimplestistoenclosetheelementsinsquarebrackets([ and ] ):
[ 1 0 ,2 0 ,3 0 ,4 0 ] [ ' c r u n c h yf r o g ' ,' r a mb l a d d e r ' ,' l a r kv o m i t ' ]
Thefirstexampleisalistoffourintegers.Thesecondisalistofthreestrings.Theelementsofalistdonthavetobethesametype.Thefollowinglist containsastring,afloat,aninteger,and(lo!)anotherlist:
[ ' s p a m ' ,2 . 0 ,5 ,[ 1 0 ,2 0 ] ]
Listsaremutable
Thesyntaxforaccessingtheelementsofalististhesameasforaccessingthecharactersofastringthebracketoperator.Theexpressioninsidethe bracketsspecifiestheindex.Rememberthattheindicesstartat0:
> > >p r i n tc h e e s e s [ 0 ] C h e d d a r
Unlikestrings,listsaremutable.Whenthebracketoperatorappearsontheleftsideofanassignment,itidentifiestheelementofthelistthatwillbeassigned.
> > >n u m b e r s=[ 1 7 ,1 2 3 ] > > >n u m b e r s [ 1 ]=5 > > >p r i n tn u m b e r s
en.wikibooks.org/wiki/Think_Python/Print_version 90/282
10/24/13
[ 1 7 ,5 ]
Theoneethelementof n u m b e r s ,whichusedtobe123,isnow5. Youcanthinkofalistasarelationshipbetweenindicesandelements.Thisrelationshipiscalleda mappingeachindexmapstooneoftheelements.Here isastatediagramshowing c h e e s e s , n u m b e r s and e m p t y : <IMGSRC="book013.png"> Listsarerepresentedbyboxeswiththewordlistoutsideandtheelementsofthelistinside. c h e e s e s referstoalistwiththreeelementsindexed0,1and2. n u m b e r s containstwoelementsthediagramshowsthatthevalueofthesecondelementhasbeenreassignedfrom123to5. e m p t y referstoalistwithno elements. Listindicesworkthesamewayasstringindices: Anyintegerexpressioncanbeusedasanindex. Ifyoutrytoreadorwriteanelementthatdoesnotexist,yougetan I n d e x E r r o r . Ifanindexhasanegativevalue,itcountsbackwardfromtheendofthelist. The i n operatoralsoworksonlists.
> > >c h e e s e s=[ ' C h e d d a r ' ,' E d a m ' ,' G o u d a ' ] > > >' E d a m 'i nc h e e s e s T r u e > > >' B r i e 'i nc h e e s e s F a l s e
Traversingalist
Themostcommonwaytotraversetheelementsofalistiswitha f o r loop.Thesyntaxisthesameasforstrings:
f o rc h e e s ei nc h e e s e s : p r i n tc h e e s e
10/24/13
Thislooptraversesthelistandupdateseachelement. l e n returnsthenumberofelementsinthelist. r a n g e returnsalistofindicesfrom0to n1,where nisthe lengthofthelist.Eachtimethroughtheloop i getstheindexofthenextelement.Theassignmentstatementinthebodyuses i toreadtheoldvalueofthe elementandtoassignthenewvalue. A f o r loopoveranemptylistneverexecutesthebody:
f o rxi ne m p t y : p r i n t' T h i sn e v e rh a p p e n s . '
Althoughalistcancontainanotherlist,thenestedliststillcountsasasingleelement.Thelengthofthislistisfour:
[ ' s p a m ' ,1 ,[ ' B r i e ' ,' R o q u e f o r t ' ,' P o ll eV e q ' ] ,[ 1 ,2 ,3 ] ]
Listoperations
The + operatorconcatenateslists:
> > >a=[ 1 ,2 ,3 ] > > >b=[ 4 ,5 ,6 ] > > >c=a+b > > >p r i n tc [ 1 ,2 ,3 ,4 ,5 ,6 ]
Similarly,the * operatorrepeatsalistagivennumberoftimes:
> > >[ 0 ]*4 [ 0 ,0 ,0 ,0 ] > > >[ 1 ,2 ,3 ]*3 [ 1 ,2 ,3 ,1 ,2 ,3 ,1 ,2 ,3 ]
Listslices
Thesliceoperatoralsoworksonlists:
> > >t=[ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ,' f ' ] > > >t [ 1 : 3 ] [ ' b ' ,' c ' ] > > >t [ : 4 ]
en.wikibooks.org/wiki/Think_Python/Print_version 92/282
10/24/13
[ ' a ' ,' b ' ,' c ' ,' d ' ] > > >t [ 3 : ] [ ' d ' ,' e ' ,' f ' ]
Ifyouomitthefirstindex,theslicestartsatthebeginning.Ifyouomitthesecond,theslicegoestotheend.Soifyouomitboth,thesliceisacopyofthe wholelist.
> > >t [ : ] [ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ,' f ' ]
Sincelistsaremutable,itisoftenusefultomakeacopybeforeperformingoperationsthatfold,spindleormutilatelists. Asliceoperatorontheleftsideofanassignmentcanupdatemultipleelements:
> > >t=[ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ,' f ' ] > > >t [ 1 : 3 ]=[ ' x ' ,' y ' ] > > >p r i n tt [ ' a ' ,' x ' ,' y ' ,' d ' ,' e ' ,' f ' ]
Listmethods
Pythonprovidesmethodsthatoperateonlists.Forexample, a p p e n d addsanewelementtotheendofalist:
> > >t=[ ' a ' ,' b ' ,' c ' ] > > >t . a p p e n d ( ' d ' ) > > >p r i n tt [ ' a ' ,' b ' ,' c ' ,' d ' ]
e x t e n d takesalistasanargumentandappendsalloftheelements:
> > >t 1=[ ' a ' ,' b ' ,' c ' ] > > >t 2=[ ' d ' ,' e ' ] > > >t 1 . e x t e n d ( t 2 ) > > >p r i n tt 1 [ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ]
Thisexampleleaves t 2 unmodified.
s o r t arrangestheelementsofthelistfromlowtohigh:
> > >t=[ ' d ' ,' c ' ,' e ' ,' b ' ,' a ' ]
en.wikibooks.org/wiki/Think_Python/Print_version 93/282
10/24/13
> > >t . s o r t ( ) > > >p r i n tt [ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ]
Map,filterandreduce
Toaddupallthenumbersinalist,youcanusealooplikethis:
d e fa d d _ a l l ( t ) : t o t a l=0 f o rxi nt : t o t a l+ =x r e t u r nt o t a l
t o t a l isinitializedto0.Eachtimethroughtheloop, x getsoneelementfromthelist.The + = operatorprovidesashortwaytoupdateavariable:
t o t a l+ =x
isequivalentto:
t o t a l=t o t a l+x
10/24/13
r e t u r nr e s
r e s isinitializedwithanemptylisteachtimethroughtheloop,weappendthenextelement.So r e s isanotherkindofaccumulator.
Exercise1
Writeafunctionthattakesalistofnumbersandreturnsthecumulativesumthatis,anewlistwherethe'i 'thelementisthesumofthefirst'i +1'elements fromtheoriginallist.Forexample,thecumulativesumof'[ 1 ,2 ,3 ] 'is'[ 1 ,3 ,6 ] '.
Deletingelements
Thereareseveralwaystodeleteelementsfromalist.Ifyouknowtheindexoftheelementyouwant,youcanuse p o p :
> > >t=[ ' a ' ,' b ' ,' c ' ] > > >x=t . p o p ( 1 ) > > >p r i n tt [ ' a ' ,' c ' ] > > >p r i n tx b
p o p modifiesthelistandreturnstheelementthatwasremoved.Ifyoudontprovideanindex,itdeletesandreturnsthelastelement.
Ifyoudontneedtheremovedvalue,youcanusethe d e l operator:
en.wikibooks.org/wiki/Think_Python/Print_version 95/282
10/24/13
> > >t=[ ' a ' ,' b ' ,' c ' ] > > >d e lt [ 1 ] > > >p r i n tt [ ' a ' ,' c ' ]
Ifyouknowtheelementyouwanttoremove(butnottheindex),youcanuse r e m o v e :
> > >t=[ ' a ' ,' b ' ,' c ' ] > > >t . r e m o v e ( ' b ' ) > > >p r i n tt [ ' a ' ,' c ' ]
Asusual,thesliceselectsalltheelementsupto,butnotincluding,thesecondindex.
Listsandstrings
Astringisasequenceofcharactersandalistisasequenceofvalues,butalistofcharactersisnotthesameasastring.Toconvertfromastringtoalistof characters,youcanuse l i s t :
> > >s=' s p a m ' > > >t=l i s t ( s ) > > >p r i n tt [ ' s ' ,' p ' ,' a ' ,' m ' ]
10/24/13
Anoptionalargumentcalleda delimiterspecifieswhichcharacterstouseaswordboundaries.Thefollowingexampleusesahyphenasadelimiter:
> > >s=' s p a m s p a m s p a m ' > > >d e l i m i t e r=' ' > > >s . s p l i t ( d e l i m i t e r ) [ ' s p a m ' ,' s p a m ' ,' s p a m ' ]
j o i n istheinverseof s p l i t .Ittakesalistofstringsandconcatenatestheelements. j o i n isastringmethod,soyouhavetoinvokeitonthedelimiterandpass
thelistasaparameter:
> > >t=[ ' p i n i n g ' ,' f o r ' ,' t h e ' ,' f j o r d s ' ] > > >d e l i m i t e r='' > > >d e l i m i t e r . j o i n ( t ) ' p i n i n gf o rt h ef j o r d s '
Objectsandvalues
Ifweexecutetheseassignmentstatements:
a=' b a n a n a ' b=' b a n a n a '
Weknowthat a and b bothrefertoastring,butwedontknowwhethertheyrefertothe samestring.Therearetwopossiblestates: <IMGSRC="book014.png"> Inonecase, a and b refertotwodifferentobjectsthathavethesamevalue.Inthesecondcase,theyrefertothesameobject. Tocheckwhethertwovariablesrefertothesameobject,youcanusethe i s operator.
> > >a=' b a n a n a ' > > >b=' b a n a n a ' > > >ai sb T r u e
10/24/13
Butwhenyoucreatetwolists,yougettwoobjects:
> > >a=[ 1 ,2 ,3 ] > > >b=[ 1 ,2 ,3 ] > > >ai sb F a l s e
Sothestatediagramlookslikethis: <IMGSRC="book015.png"> Inthiscasewewouldsaythatthetwolistsare equivalent,becausetheyhavethesameelements,butnot identical ,becausetheyarenotthesameobject.If twoobjectsareidentical,theyarealsoequivalent,butiftheyareequivalent,theyarenotnecessarilyidentical. Untilnow,wehavebeenusingobjectandvalueinterchangeably,butitismoreprecisetosaythatanobjecthasavalue.Ifyouexecute a=[ 1 , 2 , 3 ] , a refers toalistobjectwhosevalueisaparticularsequenceofelements.Ifanotherlisthasthesameelements,wewouldsayithasthesamevalue.
Aliasing
If a referstoanobjectandyouassign b=a ,thenbothvariablesrefertothesameobject:
> > >a=[ 1 ,2 ,3 ] > > >b=a > > >bi sa T r u e
Althoughthisbehaviorcanbeuseful,itiserrorprone.Ingeneral,itissafertoavoidaliasingwhenyouareworkingwithmutableobjects. Forimmutableobjectslikestrings,aliasingisnotasmuchofaproblem.Inthisexample:
en.wikibooks.org/wiki/Think_Python/Print_version 98/282
10/24/13
Listarguments
Whenyoupassalisttoafunction,thefunctiongetsareferencetothelist.Ifthefunctionmodifiesalistparameter,thecallerseesthechange.Forexample, d e l e t e _ h e a d removesthefirstelementfromalist:
d e fd e l e t e _ h e a d ( t ) : d e lt [ 0 ]
Hereshowitisused:
> > >l e t t e r s=[ ' a ' ,' b ' ,' c ' ] > > >d e l e t e _ h e a d ( l e t t e r s ) > > >p r i n tl e t t e r s [ ' b ' ,' c ' ]
en.wikibooks.org/wiki/Think_Python/Print_version
99/282
10/24/13
#W R O N G !
Thisfunctionleavestheoriginallistunmodified.Hereshowitisused:
> > >l e t t e r s=[ ' a ' ,' b ' ,' c ' ] > > >r e s t=t a i l ( l e t t e r s ) > > >p r i n tr e s t [ ' b ' ,' c ' ]
Exercise2
Writeafunctioncalled'c h o p 'thattakesalistandmodifiesit,removingthefirstandlastelements,andreturns'N o n e '. Thenwriteafunctioncalled'm i d d l e 'thattakesalistandreturnsanewlistthatcontainsallbutthefirstandlastelements.
Debugging
Carelessuseoflists(andothermutableobjects)canleadtolonghoursofdebugging.Herearesomecommonpitfallsandwaystoavoidthem: Dontforgetthatmostlistmethodsmodifytheargumentand return N o n e .Thisistheoppositeofthestringmethods,whichreturnanewstringandleavetheoriginalalone.Ifyouareusedtowritingstringcodelikethis:
w o r d=w o r d . s t r i p ( )
Itistemptingtowritelistcodelikethis:
t=t . s o r t ( ) #W R O N G !
en.wikibooks.org/wiki/Think_Python/Print_version
100/282
10/24/13
Because s o r t returns N o n e ,thenextoperationyouperformwith t islikelytofail. Beforeusinglistmethodsandoperators,youshouldreadthedocumentationcarefullyandthentestthemininteractivemode.Themethodsandoperatorsthat listssharewithothersequences(likestrings)aredocumentedat d o c s . p y t h o n . o r g / l i b / t y p e s s e q . h t m l .Themethodsandoperatorsthatonlyapplytomutable sequencesaredocumentedat d o c s . p y t h o n . o r g / l i b / t y p e s s e q m u t a b l e . h t m l . Pickanidiomandstickwithit. Partoftheproblemwithlistsisthattherearetoomanywaystodothings.Forexample,toremoveanelementfromalist,youcanuse p o p , r e m o v e , d e l ,oreven asliceassignment. Toaddanelement,youcanusethe a p p e n d methodorthe + operator.Butdontforgetthattheseareright:
t . a p p e n d ( x ) t=t+[ x ]
Andthesearewrong:
t . a p p e n d ( [ x ] ) t=t . a p p e n d ( x ) t+[ x ] t=t+x #W R O N G ! #W R O N G ! #W R O N G ! #W R O N G !
Ifyouwanttouseamethodlike s o r t thatmodifiestheargument,butyouneedtokeeptheoriginallistaswell,youcanmakeacopy.
o r i g=t [ : ] t . s o r t ( )
Glossary
en.wikibooks.org/wiki/Think_Python/Print_version 101/282
10/24/13
list: Asequenceofvalues. element: Oneofthevaluesinalist(orothersequence),alsocalleditems. index: Anintegervaluethatindicatesanelementinalist. nestedlist: Alistthatisanelementofanotherlist. listtraversal: Thesequentialaccessingofeachelementinalist. mapping: Arelationshipinwhicheachelementofonesetcorrespondstoanelementofanotherset.Forexample,alistisamappingfromindicestoelements. accumulator: Avariableusedinalooptoadduporaccumulatearesult. reduce: Aprocessingpatternthattraversesasequenceandaccumulatestheelementsintoasingleresult. map: Aprocessingpatternthattraversesasequenceandperformsanoperationoneachelement. filter: Aprocessingpatternthattraversesalistandselectstheelementsthatsatisfysomecriterion. object: Somethingavariablecanreferto.Anobjecthasatypeandavalue. equivalent: Havingthesamevalue. identical: Beingthesameobject(whichimpliesequivalence). reference: Theassociationbetweenavariableanditsvalue. aliasing: Acircumstancewheretwovariablesrefertothesameobject. delimiter: Acharacterorstringusedtoindicatewhereastringshouldbesplit.
Exercises
Exercise3
en.wikibooks.org/wiki/Think_Python/Print_version 102/282
10/24/13
Writeafunctioncalled i s _ s o r t e d thattakesalistasaparameterandreturns'T r u e 'ifthelistissortedinascendingorderand'F a l s e 'otherwise.Youcanassume (asaprecondition)thattheelementsofthelistcanbecomparedwiththecomparisonoperators'< ','> ',etc. Forexample, i s _ s o r t e d ( [ 1 , 2 , 2 ] ) shouldreturn'T r u e 'and i s _ s o r t e d ( [ ' b ' , ' a ' ] ) shouldreturn'F a l s e '.
Exercise4
Twowordsareanagramsifyoucanrearrangethelettersfromonetospelltheother.Writeafunctioncalled i s _ a n a g r a m thattakestwostringsandreturns'T r u e 'if theyareanagrams. Exercise5 The(socalled)BirthdayParadox: Writeafunctioncalled h a s _ d u p l i c a t e s thattakesalistandreturns'T r u e 'ifthereisanyelementthatappearsmorethanonce.Itshouldnotmodifytheoriginallist. Ifthereare23studentsinyourclass,whatarethechances thattwoofyouhavethesamebirthday?Youcanestimatethisprobabilitybygeneratingrandomsamplesof23birthdaysandcheckingformatches.Hint:you cangeneraterandombirthdayswiththe'r a n d i n t 'functioninthe'r a n d o m 'module. Youcanreadaboutthisproblemat 'w i k i p e d i a . o r g / w i k i / B i r t h d a y _ p a r a d o x ',andyoucanseemysolutionat't h i n k p y t h o n . c o m / c o d e / b i r t h d a y . p y '. Exercise6 Writeafunctioncalled r e m o v e _ d u p l i c a t e s thattakesalistandreturnsanewlistwithonlytheuniqueelementsfromtheoriginal.Hint:theydonthavetobeinthe sameorder.
Exercise7
Writeafunctionthatreadsthefile'w o r d s . t x t 'andbuildsalistwithoneelementperword.Writetwoversionsofthisfunction,oneusingthe'a p p e n d 'methodand theotherusingtheidiom't=t+[ x ] '.Whichonetakeslongertorun?Why? Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / w o r d l i s t . p y '.
Exercise8
Tocheckwhetherawordisinthewordlist,youcouldusethe'i n 'operator,butitwouldbeslowbecauseitsearchesthroughthewordsinorder. Becausethewordsareinalphabeticalorder,wecanspeedthingsupwithabisectionsearch,whichissimilartowhatyoudowhenyoulookawordupinthe dictionary.Youstartinthemiddleandchecktoseewhetherthewordyouarelookingforcomesbeforethewordinthemiddleofthelist.Ifso,thenyousearch thefirsthalfofthelistthesameway.Otherwiseyousearchthesecondhalf.
10/24/13
Exercise9
Twowordsareareversepairifeachisthereverseoftheother.Writeaprogramthatfindsallthereversepairsinthewordlist.
Exercise10
Twowordsinterlockiftakingalternatinglettersfromeachformsanewword1.Forexample,shoeandcoldinterlocktoformschooled. Writeaprogramthatfindsallpairsofwordsthatinterlock. Hint:dontenumerateallpairs! Canyoufindanywordsthatarethreewayinterlockedthatis, everythirdletterformsaword,startingfromthefirst,secondorthird?
1 Thisexerciseisinspiredbyanexampleat p u z z l e r s . o r g .
Dictionaries
A dictionaryislikealist,butmoregeneral.Inalist,theindiceshavetobeintegersinadictionarytheycanbe(almost)anytype. Youcanthinkofadictionaryasamappingbetweenasetofindices(whicharecalled keys)andasetofvalues.Eachkeymapstoavalue.Theassociationof akeyandavalueiscalleda keyvaluepairorsometimesan item. Asanexample,we'llbuildadictionarythatmapsfromEnglishtoSpanishwords,sothekeysandthevaluesareallstrings. Thefunction d i c t createsanewdictionarywithnoitems.Because d i c t isthenameofabuiltinfunction,youshouldavoidusingitasavariablename.
> > >e n g 2 s p=d i c t ( ) > > >p r i n te n g 2 s p { }
en.wikibooks.org/wiki/Think_Python/Print_version
104/282
10/24/13
Thesquigglybrackets, { } ,representanemptydictionary.Toadditemstothedictionary,youcanusesquarebrackets:
> > >e n g 2 s p [ ' o n e ' ]=' u n o '
Thisoutputformatisalsoaninputformat.Forexample,youcancreateanewdictionarywiththreeitems:
> > >e n g 2 s p={ ' o n e ' :' u n o ' ,' t w o ' :' d o s ' ,' t h r e e ' :' t r e s ' }
Butifyouprint e n g 2 s p ,youmightbesurprised:
> > >p r i n te n g 2 s p { ' o n e ' :' u n o ' ,' t h r e e ' :' t r e s ' ,' t w o ' :' d o s ' }
The l e n functionworksondictionariesitreturnsthenumberofkeyvaluepairs:
> > >l e n ( e n g 2 s p )
en.wikibooks.org/wiki/Think_Python/Print_version 105/282
10/24/13
Exercise1
Writeafunctionthatreadsthewordsin'w o r d s . t x t 'andstoresthemaskeysinadictionary.Itdoesntmatterwhatthevaluesare.Thenyoucanusethe'i n ' operatorasafastwaytocheckwhetherastringisinthedictionary. IfyoudidExercise'10.8',youcancomparethespeedofthisimplementationwiththelist'i n 'operatorandthebisectionsearch.
Dictionaryasasetofcounters
Supposeyouaregivenastringandyouwanttocounthowmanytimeseachletterappears.Thereareseveralwaysyoucoulddoit: Youcouldcreate26variables,oneforeachletterofthealphabet.Thenyoucouldtraversethestringand,foreachcharacter,incrementthe correspondingcounter,probablyusingachainedconditional. Youcouldcreatealistwith26elements.Thenyoucouldconverteachcharactertoanumber(usingthebuiltinfunction o r d ),usethenumberasan indexintothelist,andincrementtheappropriatecounter. Youcouldcreateadictionarywithcharactersaskeysandcountersasthecorrespondingvalues.Thefirsttimeyouseeacharacter,youwouldaddan itemtothedictionary.Afterthatyouwouldincrementthevalueofanexistingitem. Eachoftheseoptionsperformsthesamecomputation,buteachofthemimplementsthatcomputationinadifferentway. An implementationisawayofperformingacomputationsomeimplementationsarebetterthanothers.Forexample,anadvantageofthedictionary en.wikibooks.org/wiki/Think_Python/Print_version
106/282
10/24/13
Exercise2
Dictionarieshaveamethodcalled'g e t 'thattakesakeyandadefaultvalue.Ifthekeyappearsinthedictionary,'g e t 'returnsthecorrespondingvalueotherwise itreturnsthedefaultvalue.Forexample:
' ' > > >h=h i s t o g r a m ( ' a ' ) > > >p r i n th { ' a ' :1 } > > >h . g e t ( ' a ' ,0 ) 1 > > >h . g e t ( ' b ' ,0 ) 0 ' '
en.wikibooks.org/wiki/Think_Python/Print_version
107/282
10/24/13
Loopinganddictionaries
Ifyouuseadictionaryina f o r statement,ittraversesthekeysofthedictionary.Forexample, p r i n t _ h i s t printseachkeyandthecorrespondingvalue:
d e fp r i n t _ h i s t ( h ) : f o rci nh : p r i n tc ,h [ c ]
Hereswhattheoutputlookslike:
> > >h=h i s t o g r a m ( ' p a r r o t ' ) > > >p r i n t _ h i s t ( h ) a1 p1 r2 t1 o1
Again,thekeysareinnoparticularorder.
Exercise3
Dictionarieshaveamethodcalled'k e y s 'thatreturnsthekeysofthedictionary,innoparticularorder,asalist. Modify p r i n t _ h i s t toprintthekeysandtheirvaluesinalphabeticalorder.
Reverselookup
Givenadictionary d andakey k ,itiseasytofindthecorrespondingvalue v=d [ k ] .Thisoperationiscalleda lookup. Butwhatifyouhave v andyouwanttofind k ?Youhavetwoproblems:first,theremightbemorethanonekeythatmapstothevalue v .Dependingonthe application,youmightbeabletopickone,oryoumighthavetomakealistthatcontainsallofthem.Second,thereisnosimplesyntaxtodoa reverse lookupyouhavetosearch. Hereisafunctionthattakesavalueandreturnsthefirstkeythatmapstothatvalue:
d e fr e v e r s e _ l o o k u p ( d ,v ) : f o rki nd : i fd [ k ]= =v : r e t u r nk r a i s eV a l u e E r r o r
en.wikibooks.org/wiki/Think_Python/Print_version
108/282
10/24/13
Andanunsuccessfulone:
> > >k=r e v e r s e _ l o o k u p ( h ,3 ) T r a c e b a c k( m o s tr e c e n tc a l ll a s t ) : F i l e" < s t d i n > " ,l i n e1 ,i n? F i l e" < s t d i n > " ,l i n e5 ,i nr e v e r s e _ l o o k u p V a l u e E r r o r
Dictionariesandlists
Listscanappearasvaluesinadictionary.Forexample,ifyouweregivenadictionarythatmapsfromletterstofrequencies,youmightwanttoinvertitthatis, createadictionarythatmapsfromfrequenciestoletters.Sincetheremightbeseveralletterswiththesamefrequency,eachvalueintheinverteddictionary shouldbealistofletters. Hereisafunctionthatinvertsadictionary:
en.wikibooks.org/wiki/Think_Python/Print_version 109/282
10/24/13
Eachtimethroughtheloop, k e y getsakeyfrom d and v a l getsthecorrespondingvalue.If v a l isnotin i n v ,thatmeanswehaventseenitbefore,sowecreatea newitemandinitializeitwitha singleton(alistthatcontainsasingleelement).Otherwisewehaveseenthisvaluebefore,soweappendthecorresponding keytothelist. Hereisanexample:
> > >h i s t=h i s t o g r a m ( ' p a r r o t ' ) > > >p r i n th i s t { ' a ' :1 ,' p ' :1 ,' r ' :2 ,' t ' :1 ,' o ' :1 } > > >i n v=i n v e r t _ d i c t ( h i s t ) > > >p r i n ti n v { 1 :[ ' a ' ,' p ' ,' t ' ,' o ' ] ,2 :[ ' r ' ] }
Imentionedearlierthatadictionaryisimplementedusingahashtableandthatmeansthatthekeyshavetobe hashable.
en.wikibooks.org/wiki/Think_Python/Print_version 110/282
10/24/13
Exercise5
Readthedocumentationofthedictionarymethod's e t d e f a u l t 'anduseittowriteamoreconciseversionof i n v e r t _ d i c t .
Memos
Ifyouplayedwiththe f i b o n a c c i functionfromSection6.7,youmighthavenoticedthatthebiggertheargumentyouprovide,thelongerthefunctiontakesto run.Furthermore,theruntimeincreasesveryquickly. Tounderstandwhy,considerthis callgraphfor f i b o n a c c i with n = 4 : <IMGSRC="book019.png"> Acallgraphshowsasetoffunctionframes,withlinesconnectingeachframetotheframesofthefunctionsitcalls.Atthetopofthegraph, f i b o n a c c i with n = 4 calls f i b o n a c c i with n = 3 and n = 2 .Inturn, f i b o n a c c i with n = 3 calls f i b o n a c c i with n = 2 and n = 1 .Andsoon. Counthowmanytimes f i b o n a c c i ( 0 ) and f i b o n a c c i ( 1 ) arecalled.Thisisaninefficientsolutiontotheproblem,anditgetsworseastheargumentgetsbigger. Onesolutionistokeeptrackofvaluesthathavealreadybeencomputedbystoringtheminadictionary.Apreviouslycomputedvaluethatisstoredforlater useiscalleda memo[12].Hereisanimplementationof f i b o n a c c i usingmemos:
k n o w n={ 0 : 0 ,1 : 1 } d e ff i b o n a c c i ( n ) : i fni nk n o w n : r e t u r nk n o w n [ n ] r e s=f i b o n a c c i ( n 1 )+f i b o n a c c i ( n 2 ) k n o w n [ n ]=r e s r e t u r nr e s
k n o w n isadictionarythatkeepstrackoftheFibonaccinumberswealreadyknow.Itstartswithtwoitems:0mapsto0and1mapsto1.
en.wikibooks.org/wiki/Think_Python/Print_version 111/282
10/24/13
Exercise6
Runthisversionof'f i b o n a c c i 'andtheoriginalwitharangeofparametersandcomparetheirruntimes.
Globalvariables
Inthepreviousexample, k n o w n iscreatedoutsidethefunction,soitbelongstothespecialframecalled _ _ m a i n _ _ .Variablesin _ _ m a i n _ _ aresometimescalled global becausetheycanbeaccessedfromanyfunction.Unlikelocalvariables,whichdisappearwhentheirfunctionends,globalvariablespersistfromone functioncalltothenext. Itiscommontouseglobalvariablesfor flagsthatis,booleanvariablesthatindicate(flag)whetheraconditionistrue.Forexample,someprogramsusea flagnamed v e r b o s e tocontrolthelevelofdetailintheoutput:
v e r b o s e=T r u e d e fe x a m p l e 1 ( ) : i fv e r b o s e : p r i n t' R u n n i n ge x a m p l e 1 '
Ifyoutrytoreassignaglobalvariable,youmightbesurprised.Thefollowingexampleissupposedtokeeptrackofwhetherthefunctionhasbeencalled:
b e e n _ c a l l e d=F a l s e d e fe x a m p l e 2 ( ) : b e e n _ c a l l e d=T r u e
#W R O N G
en.wikibooks.org/wiki/Think_Python/Print_version
112/282
10/24/13
Heresanexamplethattriestoupdateaglobalvariable:
c o u n t=0 d e fe x a m p l e 3 ( ) : c o u n t=c o u n t+1
#W R O N G
Ifyourunityouget:
U n b o u n d L o c a l E r r o r :l o c a lv a r i a b l e' c o u n t 'r e f e r e n c e db e f o r ea s s i g n m e n t
Iftheglobalvalueismutable,youcanmodifyitwithoutdeclaringit:
k n o w n={ 0 : 0 ,1 : 1 } d e fe x a m p l e 4 ( ) : k n o w n [ 2 ]=1
Soyoucanadd,removeandreplaceelementsofagloballistordictionary,butifyouwanttoreassignthevariable,youhavetodeclareit:
d e fe x a m p l e 5 ( ) : g l o b a lk n o w n k n o w n=d i c t ( )
Longintegers
Ifyoucompute f i b o n a c c i ( 5 0 ) ,youget:
> > >f i b o n a c c i ( 5 0 ) 1 2 5 8 6 2 6 9 0 2 5 L
The L attheendindicatesthattheresultisalonginteger[13],ortype l o n g .
en.wikibooks.org/wiki/Think_Python/Print_version 113/282
10/24/13
Inthefirstcasetheresulthastype i n t inthesecondcaseitis l o n g .
Exercise7
Exponentiationoflargeintegersisthebasisofcommonalgorithmsforpublickeyencryption.ReadtheWikipediapageontheRSAalgorithm[14]andwrite functionstoencodeanddecodemessages.
Debugging
Asyouworkwithbiggerdatasetsitcanbecomeunwieldytodebugbyprintingandcheckingdatabyhand.Herearesomesuggestionsfordebugginglarge datasets: Scaledowntheinput: Ifpossible,reducethesizeofthedataset.Forexampleiftheprogramreadsatextfile,startwithjustthefirst10lines,orwiththesmallestexample youcanfind.Youcaneithereditthefilesthemselves,or(better)modifytheprogramsoitreadsonlythefirst n lines.Ifthereisanerror,youcanreduce
n tothesmallestvaluethatmanifeststheerror,andthenincreaseitgraduallyasyoufindandcorrecterrors.
Checksummariesandtypes: Insteadofprintingandcheckingtheentiredataset,considerprintingsummariesofthedata:forexample,thenumberofitemsinadictionaryorthe totalofalistofnumbers.Acommoncauseofruntimeerrorsisavaluethatisnottherighttype.Fordebuggingthiskindoferror,itisoftenenoughto printthetypeofavalue. Writeselfchecks: Sometimesyoucanwritecodetocheckforerrorsautomatically.Forexample,ifyouarecomputingtheaverageofalistofnumbers,youcouldcheck thattheresultisnotgreaterthanthelargestelementinthelistorlessthanthesmallest.Thisiscalledasanitycheckbecauseitdetectsresultsthat areinsane.Anotherkindofcheckcomparestheresultsoftwodifferentcomputationstoseeiftheyareconsistent.Thisiscalledaconsistencycheck. Prettyprinttheoutput: Formattingdebuggingoutputcanmakeiteasiertospotanerror.WesawanexampleinSection6.9.The p p r i n t moduleprovidesa p p r i n t functionthat displaysbuiltintypesinamorehumanreadableformat. Again,timeyouspendbuildingscaffoldingcanreducethetimeyouspenddebugging.
en.wikibooks.org/wiki/Think_Python/Print_version 114/282
10/24/13
Glossary
dictionary: Amappingfromasetofkeystotheircorrespondingvalues. keyvaluepair: Therepresentationofthemappingfromakeytoavalue. item: Anothernameforakeyvaluepair. key: Anobjectthatappearsinadictionaryasthefirstpartofakeyvaluepair. value: Anobjectthatappearsinadictionaryasthesecondpartofakeyvaluepair.Thisismorespecificthanourprevioususeofthewordvalue. implementation: Awayofperformingacomputation. hashtable: ThealgorithmusedtoimplementPythondictionaries. hashfunction: Afunctionusedbyahashtabletocomputethelocationforakey. hashable: Atypethathasahashfunction.Immutabletypeslikeintegers,floatsandstringsarehashablemutabletypeslikelistsanddictionariesarenot. lookup: Adictionaryoperationthattakesakeyandfindsthecorrespondingvalue. reverselookup: Adictionaryoperationthattakesavalueandfindsoneormorekeysthatmaptoit. singleton: Alist(orothersequence)withasingleelement. callgraph: Adiagramthatshowseveryframecreatedduringtheexecutionofaprogram,withanarrowfromeachcallertoeachcallee. histogram: Asetofcounters. memo: Acomputedvaluestoredtoavoidunnecessaryfuturecomputation. globalvariable: Avariabledefinedoutsideafunction.Globalvariablescanbeaccessedfromanyfunction. flag: Abooleanvariableusedtoindicatewhetheraconditionistrue.
en.wikibooks.org/wiki/Think_Python/Print_version 115/282
10/24/13
Exercise8
D i c t i o n a r i e sh a v eam e t h o dc a l l e d' k e y s 't h a tr e t u r n st h ek e y so ft h ed i c t i o n a r y ,i n
noparticularorder,asalist.Modifyprint_histtoprintthekeysandtheirvaluesinalphabeticalorder.
Exercise9
Twowordsarerotatepairsifyoucanrotateoneofthemandgettheother(see r o t a t e _ w o r d inExercise'8.12'). Writeaprogramthatreadsawordlistandfindsalltherotatepairs.
Exercise10
HeresanotherPuzzlerfromCarTalk[15]: ThiswassentinbyafellownamedDanOLeary.Hecameuponacommononesyllable,fiveletterwordrecentlythathasthefollowingunique property.Whenyouremovethefirstletter,theremaininglettersformahomophoneoftheoriginalword,thatisawordthatsoundsexactlythe same.Replacethefirstletter,thatis,putitbackandremovethesecondletterandtheresultisyetanotherhomophoneoftheoriginalword.And thequestionis,whatstheword? NowImgoingtogiveyouanexamplethatdoesntwork.Letslookat thefiveletterword,wrack.WRACK, youknowliketowrackwithpain.IfIremovethefirstletter,Iamleftwithafourletterword,RACK.Asin,Holycow,didyouseetherackon thatbuck!Itmusthavebeenaninepointer!Itsaperfecthomophone.Ifyouputthewback,andremovether,instead,youreleftwiththe word,wack,whichisarealword,itsjustnotahomophoneoftheothertwowords. Butthereis,however,atleastonewordthatDanandweknowof, whichwillyieldtwohomophonesifyouremoveeitherofthefirsttwolettersto maketwo,newfourletterwords.Thequestionis,whatstheword? ' YoucanusethedictionaryfromExercise'11.1'tocheckwhetherastringisinthewordlist. Tocheckwhethertwowordsarehomophones,youcanusetheCMUPronouncingDictionary.Youcandownloaditfrom'w w w . s p e e c h . c s . c m u . e d u / c g i b i n / c m u d i c t 'or from't h i n k p y t h o n . c o m / c o d e / c 0 6 d 'andyoucanalsodownload't h i n k p y t h o n . c o m / c o d e / p r o n o u n c e . p y ',whichprovidesafunctionnamed r e a d _ d i c t i o n a r y thatreadsthe pronouncingdictionaryandreturnsaPythondictionarythatmapsfromeachwordtoastringthatdescribesitsprimarypronunciation. WriteaprogramthatlistsallthewordsthatsolvethePuzzler. Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / h o m o p h o n e . p y '.
Notes
en.wikibooks.org/wiki/Think_Python/Print_version 116/282
10/24/13
Tuples
Tuplesareimmutable
Atupleisasequenceofvalues.Thevaluescanbeanytype,andtheyareindexedbyintegers,sointhatrespecttuplesarealotlikelists.Theimportant differenceisthattuplesareimmutable. Syntactically,atupleisacommaseparatedlistofvalues:
> > >t=' a ' ,' b ' ,' c ' ,' d ' ,' e '
Althoughitisnotnecessary,itiscommontoenclosetuplesinparentheses:
> > >t=( ' a ' ,' b ' ,' c ' ,' d ' ,' e ' )
Tocreateatuplewithasingleelement,youhavetoincludethefinalcomma:
> > >t 1=( ' a ' , ) > > >t y p e ( t 1 ) < t y p e' t u p l e ' >
Anotherwaytocreateatupleisthebuiltinfunction t u p l e .Withnoargument,itcreatesanemptytuple:
> > >t=t u p l e ( ) > > >p r i n tt ( )
Iftheargumentisasequence(string,listortuple),theresultisatuplewiththeelementsofthesequence:
> > >t=t u p l e ( ' l u p i n s ' ) > > >p r i n tt
en.wikibooks.org/wiki/Think_Python/Print_version 117/282
10/24/13
( ' l ' ,' u ' ,' p ' ,' i ' ,' n ' ,' s ' )
Andthesliceoperatorselectsarangeofelements.
> > >p r i n tt [ 1 : 3 ] ( ' b ' ,' c ' )
Butifyoutrytomodifyoneoftheelementsofthetuple,yougetanerror:
> > >t [ 0 ]=' A ' T y p e E r r o r :o b j e c td o e s n ' ts u p p o r ti t e ma s s i g n m e n t
Youcantmodifytheelementsofatuple,butyoucanreplaceonetuplewithanother:
> > >t=( ' A ' , )+t [ 1 : ] > > >p r i n tt ( ' A ' ,' b ' ,' c ' ,' d ' ,' e ' )
Tupleassignment
Itisoftenusefultoswapthevaluesoftwovariables.Withconventionalassignments,youhavetouseatemporaryvariable.Forexample,toswap a and b :
> > >t e m p=a > > >a=b > > >b=t e m p
Thissolutioniscumbersome tupleassignmentismoreelegant:
> > >a ,b=b ,a
en.wikibooks.org/wiki/Think_Python/Print_version
118/282
10/24/13
Moregenerally,therightsidecanbeanykindofsequence(string,listortuple).Forexample,tosplitanemailaddressintoausernameandadomain,you couldwrite:
> > >a d d r=' m o n t y @ p y t h o n . o r g ' > > >u n a m e ,d o m a i n=a d d r . s p l i t ( ' @ ' )
Tuplesasreturnvalues
Strictlyspeaking,afunctioncanonlyreturnonevalue,butifthevalueisatuple,theeffectisthesameasreturningmultiplevalues.Forexample,ifyouwant todividetwointegersandcomputethequotientandremainder,itisinefficienttocompute x / y andthen x % y .Itisbettertocomputethembothatthesame time. Thebuiltinfunction d i v m o d takestwoargumentsandreturnsatupleoftwovalues,thequotientandremainder.Youcanstoretheresultasatuple:
> > >t=d i v m o d ( 7 ,3 ) > > >p r i n tt ( 2 ,1 )
Orusetupleassignmenttostoretheelementsseparately:
> > >q u o t ,r e m=d i v m o d ( 7 ,3 ) > > >p r i n tq u o t 2 > > >p r i n tr e m 1
en.wikibooks.org/wiki/Think_Python/Print_version
119/282
10/24/13
Hereisanexampleofafunctionthatreturnsatuple:
d e fm i n _ m a x ( t ) : r e t u r nm i n ( t ) ,m a x ( t )
m a x and m i n arebuiltinfunctionsthatfindthelargestandsmallestelementsofasequence. m i n _ m a x computesbothandreturnsatupleoftwovalues.
Variablelengthargumenttuples
Functionscantakeavariablenumberofarguments.Aparameternamethatbeginswith * gathersargumentsintoatuple.Forexample, p r i n t a l l takesany numberofargumentsandprintsthem:
d e fp r i n t a l l ( * a r g s ) : p r i n ta r g s
Thegatherparametercanhaveanynameyoulike,but a r g s isconventional.Hereshowthefunctionworks:
> > >p r i n t a l l ( 1 ,2 . 0 ,' 3 ' ) ( 1 ,2 . 0 ,' 3 ' )
Youcancombinethegatheroperatorwithrequiredandpositionalarguments:
d e fp o i n t l e s s ( r e q u i r e d ,o p t i o n a l = 0 ,* a r g s ) : p r i n tr e q u i r e d ,o p t i o n a l ,a r g s
Butifyouscatterthetuple,itworks:
> > >d i v m o d ( * t ) ( 2 ,1 )
en.wikibooks.org/wiki/Think_Python/Print_version
120/282
10/24/13
Exercise1
Manyofthebuiltinfunctionsusevariablelengthargumenttuples.Forexample,'m a x 'and'm i n 'cantakeanynumberofarguments:
' ' > > >m a x ( 1 , 2 , 3 ) 3 ' '
But's u m 'doesnot.
' ' > > >s u m ( 1 , 2 , 3 ) T y p e E r r o r :s u me x p e c t e da tm o s t2a r g u m e n t s ,g o t3 ' '
Writeafunctioncalled's u m a l l 'thattakesanynumberofargumentsandreturnstheirsum.
Listsandtuples
z i p isabuiltinfunctionthattakestwoormoresequencesandzipsthemintoalist 1oftupleswhereeachtuplecontainsoneelementfromeachsequence.
Thisexamplezipsastringandalist:
> > >s=' a b c ' > > >t=[ 0 ,1 ,2 ] > > >z i p ( s ,t ) [ ( ' a ' ,0 ) ,( ' b ' ,1 ) ,( ' c ' ,2 ) ]
Theresultisalistoftupleswhereeachtuplecontainsacharacterfromthestringandthecorrespondingelementfromthelist. Ifthesequencesarenotthesamelength,theresulthasthelengthoftheshorterone.
> > >z i p ( ' A n n e ' ,' E l k ' ) [ ( ' A ' ,' E ' ) ,( ' n ' ,' l ' ) ,( ' n ' ,' k ' ) ]
Youcanusetupleassignmentina f o r looptotraversealistoftuples:
t=[ ( ' a ' ,0 ) ,( ' b ' ,1 ) ,( ' c ' ,2 ) ] f o rl e t t e r ,n u m b e ri nt : p r i n tn u m b e r ,l e t t e r
en.wikibooks.org/wiki/Think_Python/Print_version
121/282
10/24/13
Ifyouneedtotraversetheelementsofasequenceandtheirindices,youcanusethebuiltinfunction e n u m e r a t e :
f o ri n d e x ,e l e m e n ti ne n u m e r a t e ( ' a b c ' ) : p r i n ti n d e x ,e l e m e n t
Theoutputofthisloopis:
0a 1b 2c
Again.
Dictionariesandtuples
Dictionarieshaveamethodcalled i t e m s thatreturnsalistoftuples,whereeachtupleisakeyvaluepair2.
> > >d={ ' a ' : 0 ,' b ' : 1 ,' c ' : 2 } > > >t=d . i t e m s ( ) > > >p r i n tt [ ( ' a ' ,0 ) ,( ' c ' ,2 ) ,( ' b ' ,1 ) ]
Asyoushouldexpectfromadictionary,theitemsareinnoparticularorder. Conversely,youcanusealistoftuplestoinitializeanewdictionary:
en.wikibooks.org/wiki/Think_Python/Print_version 122/282
10/24/13
> > >t=[ ( ' a ' ,0 ) ,( ' c ' ,2 ) ,( ' b ' ,1 ) ] > > >d=d i c t ( t ) > > >p r i n td { ' a ' :0 ,' c ' :2 ,' b ' :1 }
Theoutputofthisloopis:
0a 2c 1b
Theexpressioninbracketsisatuple.Wecouldusetupleassignmenttotraversethisdictionary.
f o rl a s t ,f i r s ti nd i r e c t o r y : p r i n tf i r s t ,l a s t ,d i r e c t o r y [ l a s t , f i r s t ]
en.wikibooks.org/wiki/Think_Python/Print_version
123/282
10/24/13
Therearetwowaystorepresenttuplesinastatediagram.Themoredetailedversionshowstheindicesandelementsjustastheyappearinalist.For example,thetuple ( ' C l e e s e ' ,' J o h n ' ) wouldappear: <IMGSRC="book020.png"> Butinalargerdiagramyoumightwanttoleaveoutthedetails.Forexample,adiagramofthetelephonedirectorymightappear: <IMGSRC="book021.png"> HerethetuplesareshownusingPythonsyntaxasagraphicalshorthand. ThetelephonenumberinthediagramisthecomplaintslinefortheBBC,sopleasedontcallit.
Comparingtuples
ThecomparisonoperatorsworkwithtuplesandothersequencesPythonstartsbycomparingthefirstelementfromeachsequence.Iftheyareequal,itgoes ontothenextelements,andsoon,untilitfindselementsthatdiffer.Subsequentelementsarenotconsidered(eveniftheyarereallybig).
> > >( 0 ,1 ,2 )<( 0 ,3 ,4 ) T r u e > > >( 0 ,1 ,2 0 0 0 0 0 0 )<( 0 ,3 ,4 ) T r u e
The s o r t functionworksthesameway.Itsortsprimarilybyfirstelement,butinthecaseofatie,itsortsbysecondelement,andsoon. Thisfeaturelendsitselftoapatterncalled DSUfor Decorate asequencebybuildingalistoftupleswithoneormoresortkeysprecedingtheelementsfromthesequence, Sort thelistoftuples,and Undecorate byextractingthesortedelementsofthesequence. Forexample,supposeyouhavealistofwordsandyouwanttosortthemfromlongesttoshortest:
d e fs o r t _ b y _ l e n g t h ( w o r d s ) : t=[ ] f o rw o r di nw o r d s : t . a p p e n d ( ( l e n ( w o r d ) ,w o r d ) ) t . s o r t ( r e v e r s e = T r u e )
en.wikibooks.org/wiki/Think_Python/Print_version
124/282
10/24/13
r e s=[ ] f o rl e n g t h ,w o r di nt : r e s . a p p e n d ( w o r d ) r e t u r nr e s
Thefirstloopbuildsalistoftuples,whereeachtupleisawordprecededbyitslength.
s o r t comparesthefirstelement,length,first,andonlyconsidersthesecondelementtobreakties.Thekeywordargument r e v e r s e = T r u e tells s o r t togoin
decreasingorder. Thesecondlooptraversesthelistoftuplesandbuildsalistofwordsindescendingorderoflength.
Exercise2
Inthisexample,tiesarebrokenbycomparingwords,sowordswiththesamelengthappearinalphabeticalorder.Forotherapplicationsyoumightwantto breaktiesatrandom.Modifythisexamplesothatwordswiththesamelengthappearinrandomorder.Hint:seethe'r a n d o m 'functioninthe'r a n d o m 'module.
Sequencesofsequences
Ihavefocusedonlistsoftuples,butalmostalloftheexamplesinthischapteralsoworkwithlistsoflists,tuplesoftuples,andtuplesoflists.Toavoid enumeratingthepossiblecombinations,itissometimeseasiertotalkaboutsequencesofsequences. Inmanycontexts,thedifferentkindsofsequences(strings,listsandtuples)canbeusedinterchangeably.Sohowandwhydoyouchooseoneovertheothers? Tostartwiththeobvious,stringsaremorelimitedthanothersequencesbecausetheelementshavetobecharacters.Theyarealsoimmutable.Ifyouneed theabilitytochangethecharactersinastring(asopposedtocreatinganewstring),youmightwanttousealistofcharactersinstead. Listsaremorecommonthantuples,mostlybecausetheyaremutable.Butthereareafewcaseswhereyoumightprefertuples: Insomecontexts,likea r e t u r n statement,itissyntacticallysimplertocreateatuplethanalist.Inothercontexts,youmightpreferalist. Ifyouwanttouseasequenceasadictionarykey,youhavetouseanimmutabletypelikeatupleorstring. Ifyouarepassingasequenceasanargumenttoafunction,usingtuplesreducesthepotentialforunexpectedbehaviorduetoaliasing. Becausetuplesareimmutable,theydontprovidemethodslike s o r t and r e v e r s e ,whichmodifyexistinglists.ButPythonprovidesthebuiltinfunctions s o r t e d and r e v e r s e d ,whichtakeanysequenceasaparameterandreturnanewlistwiththesameelementsinadifferentorder.
Debugging
Lists,dictionariesandtuplesareknowngenericallyas datastructuresinthischapterwearestartingtoseecompounddatastructures,likelistsoftuples, anddictionariesthatcontaintuplesaskeysandlistsasvalues.Compounddatastructuresareuseful,buttheyarepronetowhatIcall shapeerrorsthatis, errorscausedwhenadatastructurehasthewrongtype,sizeorcomposition.Forexample,ifyouareexpectingalistwithoneintegerandIgiveyouaplainold integer(notinalist),itwontwork.
125/282
10/24/13
Afancierprogrammightwritelistof3int s,butitwaseasiernottodealwithplurals.Heresalistoflists:
> > >t 2=[ [ 1 , 2 ] ,[ 3 , 4 ] ,[ 5 , 6 ] ] > > >p r i n ts t r u c t s h a p e ( t 2 ) l i s to f3l i s to f2i n t
Iftheelementsofthelistarenotthesametype, s t r u c t s h a p e groupsthem,inorder,bytype:
> > >t 3=[ 1 ,2 ,3 ,4 . 0 ,' 5 ' ,' 6 ' ,[ 7 ] ,[ 8 ] ,9 ] > > >p r i n ts t r u c t s h a p e ( t 3 ) l i s to f( 3i n t ,f l o a t ,2s t r ,2l i s to fi n t ,i n t )
Heresalistoftuples:
> > >s=' a b c ' > > >l t=z i p ( t ,s ) > > >p r i n ts t r u c t s h a p e ( l t ) l i s to f3t u p l eo f( i n t ,s t r )
Andheresadictionarywith3itemsthatmapintegerstostrings.
> > >d=d i c t ( l t ) > > >p r i n ts t r u c t s h a p e ( d ) d i c to f3i n t > s t r
Ifyouarehavingtroublekeepingtrackofyourdatastructures, s t r u c t s h a p e canhelp.
Glossary
tuple:
en.wikibooks.org/wiki/Think_Python/Print_version 126/282
10/24/13
Animmutablesequenceofelements. tupleassignment: Anassignmentwithasequenceontherightsideandatupleofvariablesontheleft.Therightsideisevaluatedandthenitselementsareassignedto thevariablesontheleft. gather: Theoperationofassemblingavariablelengthargumenttuple. scatter: Theoperationoftreatingasequenceasalistofarguments. DSU: Abbreviationofdecoratesortundecorate,apatternthatinvolvesbuildingalistoftuples,sorting,andextractingpartoftheresult. datastructure: Acollectionofrelatedvalues,oftenorganizedinlists,dictionaries,tuples,etc. shape(ofadatastructure): Asummaryofthetype,sizeandcompositionofadatastructure.
Exercises
Exercise3
Writeafunctioncalled m o s t _ f r e q u e n t thattakesastringandprintsthelettersindecreasingorderoffrequency.Findtextsamplesfromseveraldifferent languagesandseehowletterfrequencyvariesbetweenlanguages.Compareyourresultswiththetablesat'w i k i p e d i a . o r g / w i k i / L e t t e r _ f r e q u e n c i e s '.
Exercise4
Moreanagrams! Writeaprogram thatreadsawordlistfromafile(seeSection'9.1')andprintsallthesetsofwordsthatareanagrams. Hereisanexampleofwhattheoutputmightlooklike:
' ' [ ' d e l t a s ' ,' d e s a l t ' ,' l a s t e d ' ,' s a l t e d ' ,' s l a t e d ' ,' s t a l e d ' ] [ ' r e t a i n e r s ' ,' t e r n a r i e s ' ] [ ' g e n e r a t i n g ' ,' g r e a t e n i n g ' ] [ ' r e s m e l t s ' ,' s m e l t e r s ' ,' t e r m l e s s ' ] ' '
10/24/13
Exercise5
HeresanotherCarTalkPuzzler4: WhatisthelongestEnglishword,thatremainsavalidEnglishword,asyouremoveitslettersoneatatime? Now,letterscanberemovedfrom eitherend,orthemiddle,butyoucantrearrangeanyoftheletters.Everytimeyoudropaletter,youwindupwithanotherEnglishword.Ifyou dothat,youreeventuallygoingtowindupwithoneletterandthattooisgoingtobeanEnglishwordonethatsfoundinthedictionary.Iwant toknowwhatsthelongestwordandhowmanylettersdoesithave? Imgoingtogiveyoualittlemodestexample:Sprite.Ok?Youstart offwithsprite,youtakealetteroff,onefromtheinterioroftheword,take theraway,andwereleftwiththewordspite,thenwetaketheeofftheend,wereleftwithspit,wetakethesoff,wereleftwithpit,it,andI. Writeaprogramtofindallwordsthatcanbereducedinthisway, andthenfindthelongestone. Thisexerciseisalittlemorechallengingthanmost,soherearesomesuggestions: Youmightwanttowriteafunctionthattakesawordand computesalistofallthewordsthatcanbeformedbyremovingoneletter.Thesearethechildrenoftheword. Recursively,awordisreducibleifanyofitschildren arereducible.Asabasecase,youcanconsidertheemptystringreducible. ThewordlistIprovided,'w o r d s . t x t ',doesnt containsingleletterwords.SoyoumightwanttoaddI,a,andtheemptystring. Toimprovetheperformanceofyourprogram,youmightwant tomemoizethewordsthatareknowntobereducible. Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / r e d u c i b l e . p y '.
en.wikibooks.org/wiki/Think_Python/Print_version 128/282
10/24/13
=Casestudy:datastructureselection}}
Wordfrequencyanalysis
Asusual,youshouldatleastattemptthefollowingexercisesbeforeyoureadmysolutions.
Exercise1
Writeaprogramthatreadsafile,breakseachlineintowords,stripswhitespaceandpunctuationfromthewords,andconvertsthemtolowercase. Hint:The's t r i n g 'moduleprovidesstringsnamed'w h i t e s p a c e ', whichcontainsspace,tab,newline,etc.,and'p u n c t u a t i o n 'whichcontainsthepunctuation characters.LetsseeifwecanmakePythonswear:
> > >i m p o r ts t r i n g > > >p r i n ts t r i n g . p u n c t u a t i o n ! " # $ % & ' ( ) * + , . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~
Exercise2
GotoProjectGutenberg('g u t e n b e r g . o r g ')anddownloadyourfavoriteoutofcopyrightbookinplaintextformat. Modifyyourprogramfromthepreviousexercisetoreadthebookyoudownloaded,skipovertheheaderinformationatthebeginningofthefile,andprocess therestofthewordsasbefore. Thenmodifytheprogramtocountthetotalnumberofwordsinthebook,andthenumberoftimeseachwordisused. Printthenumberofdifferentwordsusedinthebook.Comparedifferentbooksbydifferentauthors,writtenindifferenteras.Whichauthorusesthemost extensivevocabulary?
en.wikibooks.org/wiki/Think_Python/Print_version
129/282
10/24/13
Exercise3
Modifytheprogramfromthepreviousexercisetoprintthe20mostfrequentlyusedwordsinthebook.
Exercise4
Modifythepreviousprogramtoreadawordlist(seeSection'9.1')andthenprintallthewordsinthebookthatarenotinthewordlist.Howmanyofthemare typos?Howmanyofthemarecommonwordsthat shouldbeinthewordlist,andhowmanyofthemarereallyobscure?
Randomnumbers
Giventhesameinputs,mostcomputerprogramsgeneratethesameoutputseverytime,sotheyaresaidtobe deterministic.Determinismisusuallyagood thing,sinceweexpectthesamecalculationtoyieldthesameresult.Forsomeapplications,though,wewantthecomputertobeunpredictable.Gamesarean obviousexample,buttherearemore. Makingaprogramtrulynondeterministicturnsouttobenotsoeasy,buttherearewaystomakeitatleastseemnondeterministic.Oneofthemistouse algorithmsthatgenerate pseudorandomnumbers.Pseudorandomnumbersarenottrulyrandombecausetheyaregeneratedbyadeterministiccomputation, butjustbylookingatthenumbersitisallbutimpossibletodistinguishthemfromrandom. The r a n d o m moduleprovidesfunctionsthatgeneratepseudorandomnumbers(whichIwillsimplycallrandomfromhereon). Thefunction r a n d o m returnsarandomfloatbetween0.0and1.0(including0.0butnot1.0).Eachtimeyoucall r a n d o m ,yougetthenextnumberinalongseries. Toseeasample,runthisloop:
i m p o r tr a n d o m f o rii nr a n g e ( 1 0 ) : x=r a n d o m . r a n d o m ( ) p r i n tx
Tochooseanelementfromasequenceatrandom,youcanuse c h o i c e :
> > >t=[ 1 ,2 ,3 ] > > >r a n d o m . c h o i c e ( t ) 2 > > >r a n d o m . c h o i c e ( t )
en.wikibooks.org/wiki/Think_Python/Print_version 130/282
10/24/13
The r a n d o m modulealsoprovidesfunctionstogeneraterandomvaluesfromcontinuousdistributionsincludingGaussian,exponential,gamma,andafewmore.
Exercise5
Writeafunctionnamed c h o o s e _ f r o m _ h i s t thattakesahistogramasdefinedinSection'11.1'andreturnsarandomvaluefromthehistogram,chosenwith probabilityinproportiontofrequency.Forexample,forthishistogram:
' ' > > >t=[ ' a ' ,' a ' ,' b ' ] > > >h=h i s t o g r a m ( t ) > > >p r i n th { ' a ' :2 ,' b ' :1 } ' '
Wordhistogram
Hereisaprogramthatreadsafileandbuildsahistogramofthewordsinthefile:
i m p o r ts t r i n g d e fp r o c e s s _ f i l e ( f i l e n a m e ) : h=d i c t ( ) f p=o p e n ( f i l e n a m e ) f o rl i n ei nf p : p r o c e s s _ l i n e ( l i n e ,h ) r e t u r nh d e fp r o c e s s _ l i n e ( l i n e ,h ) : l i n e=l i n e . r e p l a c e ( ' ' ,'' ) f o rw o r di nl i n e . s p l i t ( ) : w o r d=w o r d . s t r i p ( s t r i n g . p u n c t u a t i o n+s t r i n g . w h i t e s p a c e ) w o r d=w o r d . l o w e r ( ) h [ w o r d ]=h . g e t ( w o r d ,0 )+1 h i s t=p r o c e s s _ f i l e ( ' e m m a . t x t ' )
10/24/13
Thenumberofdifferentwordsisjustthenumberofitemsinthedictionary:
d e fd i f f e r e n t _ w o r d s ( h ) : r e t u r nl e n ( h )
Hereissomecodetoprinttheresults:
p r i n t' T o t a ln u m b e ro fw o r d s : ' ,t o t a l _ w o r d s ( h i s t ) p r i n t' N u m b e ro fd i f f e r e n tw o r d s : ' ,d i f f e r e n t _ w o r d s ( h i s t )
Andtheresults:
T o t a ln u m b e ro fw o r d s :1 6 1 0 7 3 N u m b e ro fd i f f e r e n tw o r d s :7 2 1 2
Mostcommonwords
Tofindthemostcommonwords,wecanapplytheDSUpattern m o s t _ c o m m o n takesahistogramandreturnsalistofwordfrequencytuples,sortedinreverse orderbyfrequency:
d e fm o s t _ c o m m o n ( h ) : t=[ ] f o rk e y ,v a l u ei nh . i t e m s ( ) : t . a p p e n d ( ( v a l u e ,k e y ) ) t . s o r t ( r e v e r s e = T r u e ) r e t u r nt
Hereisaloopthatprintsthetenmostcommonwords:
en.wikibooks.org/wiki/Think_Python/Print_version 132/282
10/24/13
Andherearetheresultsfrom Emma:
T h em o s tc o m m o nw o r d sa r e : t o 5 2 4 2 t h e 5 2 0 4 a n d 4 8 9 7 o f 4 2 9 3 i 3 1 9 1 a 3 1 3 0 i t 2 5 2 9 h e r 2 4 8 3 w a s 2 4 0 0 s h e 2 3 6 4
Optionalparameters
Wehaveseenbuiltinfunctionsandmethodsthattakeavariablenumberofarguments.Itispossibletowriteuserdefinedfunctionswithoptionalarguments, too.Forexample,hereisafunctionthatprintsthemostcommonwordsinahistogram
d e fp r i n t _ m o s t _ c o m m o n ( h i s t ,n u m = 1 0 ) t=m o s t _ c o m m o n ( h i s t ) p r i n t' T h em o s tc o m m o nw o r d sa r e : ' f o rf r e q ,w o r di nt [ 0 : n u m ] : p r i n tw o r d ,' \ t ' ,f r e q
p r i n t _ m o s t _ c o m m o n ( h i s t ,2 0 )
n u m getsthevalueoftheargumentinstead.Inotherwords,theoptionalargument overridesthedefaultvalue.
en.wikibooks.org/wiki/Think_Python/Print_version 133/282
10/24/13
Ifafunctionhasbothrequiredandoptionalparameters,alltherequiredparametershavetocomefirst,followedbytheoptionalones.
Dictionarysubtraction
Findingthewordsfromthebookthatarenotinthewordlistfrom w o r d s . t x t isaproblemyoumightrecognizeassetsubtractionthatis,wewanttofindallthe wordsfromoneset(thewordsinthebook)thatarenotinanotherset(thewordsinthelist).
s u b t r a c t takesdictionaries d 1 and d 2 andreturnsanewdictionarythatcontainsallthekeysfrom d 1 thatarenotin d 2 .Sincewedontreallycareaboutthevalues,
wesetthemalltoNone.
d e fs u b t r a c t ( d 1 ,d 2 ) : r e s=d i c t ( ) f o rk e yi nd 1 : i fk e yn o ti nd 2 : r e s [ k e y ]=N o n e r e t u r nr e s
Herearesomeoftheresultsfrom Emma:
T h ew o r d si nt h eb o o kt h a ta r e n ' ti nt h ew o r dl i s ta r e : r e n c o n t r ej a n e ' sb l a n c h ew o o d h o u s e sd i s i n g e n u o u s n e s s f r i e n d ' sv e n i c ea p a r t m e n t. . .
Someofthesewordsarenamesandpossessives.Others,likerencontre,arenolongerincommonuse.Butafewarecommonwordsthatshouldreallybein thelist!
Exercise6
Pythonprovidesadatastructurecalled's e t 'thatprovidesmanycommonsetoperations.Readthedocumentationat'd o c s . p y t h o n . o r g / l i b / t y p e s s e t . h t m l 'andwritea programthatusessetsubtractiontofindwordsinthebookthatarenotinthewordlist.
Randomwords
en.wikibooks.org/wiki/Think_Python/Print_version 134/282
10/24/13
Tochoosearandomwordfromthehistogram,thesimplestalgorithmistobuildalistwithmultiplecopiesofeachword,accordingtotheobservedfrequency, andthenchoosefromthelist:
d e fr a n d o m _ w o r d ( h ) : t=[ ] f o rw o r d ,f r e qi nh . i t e m s ( ) : t . e x t e n d ( [ w o r d ]*f r e q ) r e t u r nr a n d o m . c h o i c e ( t )
Exercise7
Thisalgorithmworks,butitisnotveryefficienteachtimeyouchoosearandomword,itrebuildsthelist,whichisasbigastheoriginalbook.Anobvious improvementistobuildthelistonceandthenmakemultipleselections,butthelistisstillbig. Analternativeis: Use'k e y s 'togetalistofthewordsinthebook. Buildalistthatcontainsthecumulativesumoftheword frequencies(seeExercise'10.1').Thelastiteminthislististhetotalnumberofwordsinthebook,'n'. Choosearandomnumberfrom1to'n'.Useabisectionsearch (SeeExercise'10.8')tofindtheindexwheretherandomnumberwouldbeinsertedinthecumulativesum. Usetheindextofindthecorrespondingwordinthewordlist. Writeaprogramthatusesthisalgorithmtochoosearandomwordfromthebook.
Markovanalysis
Ifyouchoosewordsfromthebookatrandom,youcangetasenseofthevocabulary,youprobablywontgetasentence:
t h i st h es m a l lr e g a r dh a r r i e tw h i c hk n i g h t l e y ' si tm o s tt h i n g s
Aseriesofrandomwordsseldommakessensebecausethereisnorelationshipbetweensuccessivewords.Forexample,inarealsentenceyouwouldexpect anarticlelikethetobefollowedbyanadjectiveoranoun,andprobablynotaverboradverb.
10/24/13
OnewaytomeasurethesekindsofrelationshipsisMarkovanalysis,whichcharacterizes,foragivensequenceofwords,theprobabilityofthewordthatcomes next.Forexample,thesong Eric,theHalfaBeebegins: Halfabee,philosophically, Must,ipsofacto,halfnotbe. Buthalfthebeehasgottobe Visavis,itsentity.Dyousee? Butcanabeebesaidtobe Ornottobeanentirebee Whenhalfthebeeisnotabee Duetosomeancientinjury? Inthistext,thephrasehalftheisalwaysfollowedbythewordbee,butthephrasethebeemightbefollowedbyeitherhasoris. TheresultofMarkovanalysisisamappingfromeachprefix(likehalftheandthebee)toallpossiblesuffixes(likehasandis). Giventhismapping,youcangeneratearandomtextbystartingwithanyprefixandchoosingatrandomfromthepossiblesuffixes.Next,youcancombinethe endoftheprefixandthenewsuffixtoformthenextprefix,andrepeat. Forexample,ifyoustartwiththeprefixHalfa,thenthenextwordhastobebee,becausetheprefixonlyappearsonceinthetext.Thenextprefixisa bee,sothenextsuffixmightbephilosophically,beordue. Inthisexamplethelengthoftheprefixisalwaystwo,butyoucandoMarkovanalysiswithanyprefixlength.Thelengthoftheprefixiscalledtheorderofthe analysis.
Exercise8
Markovanalysis: WriteaprogramtoreadatextfromafileandperformMarkovanalysis.Theresultshouldbeadictionarythatmapsfromprefixestoacollectionof possiblesuffixes.Thecollectionmightbealist,tuple,ordictionaryitisuptoyoutomakeanappropriatechoice.Youcantestyourprogramwithprefix lengthtwo,butyoushouldwritetheprograminawaythatmakesiteasytotryotherlengths. AddafunctiontothepreviousprogramtogeneraterandomtextbasedontheMarkovanalysis.HereisanexamplefromEmma withprefixlength2: Hewasveryclever,beitsweetnessorbeangry,ashamedoronly amused,atsuchastroke.ShehadneverthoughtofHannahtillyouwerenevermeantforme?""Icannotmakespeeches,Emma:"hesooncut itallhimself. Forthisexample,Ileftthepunctuationattachedtothewords.Theresultisalmostsyntacticallycorrect,butnotquite.Semantically,italmostmakessense, butnotquite. Whathappensifyouincreasetheprefixlength?Doestherandomtextmakemoresense? Onceyourprogramisworking,youmightwanttotryamashup:ifyouanalyzetextfromtwoormorebooks,therandomtextyougeneratewillblend
en.wikibooks.org/wiki/Think_Python/Print_version 136/282
10/24/13
thevocabularyandphrasesfromthesourcesininterestingways.
Datastructures
UsingMarkovanalysistogeneraterandomtextisfun,butthereisalsoapointtothisexercise:datastructureselection.Inyoursolutiontotheprevious exercises,youhadtochoose: Howtorepresenttheprefixes. Howtorepresentthecollectionofpossiblesuffixes. Howtorepresentthemappingfromeachprefixtothecollectionofpossiblesuffixes. Ok,thelastoneistheeasytheonlymappingtypewehaveseenisadictionary,soitisthenaturalchoice. Fortheprefixes,themostobviousoptionsarestring,listofstrings,ortupleofstrings.Forthesuffixes,oneoptionisalistanotherisahistogram(dictionary). Howshouldyouchoose?Thefirststepistothinkabouttheoperationsyouwillneedtoimplementforeachdatastructure.Fortheprefixes,weneedtobeable toremovewordsfromthebeginningandaddtotheend.Forexample,ifthecurrentprefixisHalfa,andthenextwordisbee,youneedtobeabletoform thenextprefix,abee. Yourfirstchoicemightbealist,sinceitiseasytoaddandremoveelements,butwealsoneedtobeabletousetheprefixesaskeysinadictionary,sothat rulesoutlists.Withtuples,youcantappendorremove,butyoucanusetheadditionoperatortoformanewtuple:
d e fs h i f t ( p r e f i x ,w o r d ) : r e t u r np r e f i x [ 1 : ]+( w o r d , )
s h i f t takesatupleofwords, p r e f i x ,andastring, w o r d ,andformsanewtuplethathasallthewordsin p r e f i x exceptthefirst,and w o r d addedtotheend.
Forthecollectionofsuffixes,theoperationsweneedtoperformincludeaddinganewsuffix(orincreasingthefrequencyofanexistingone),andchoosinga randomsuffix. Addinganewsuffixisequallyeasyforthelistimplementationorthehistogram.Choosingarandomelementfromalistiseasychoosingfromahistogramis hardertodoefficiently(seeExercise13.7). Sofarwehavebeentalkingmostlyabouteaseofimplementation,butthereareotherfactorstoconsiderinchoosingdatastructures.Oneisruntime. Sometimesthereisatheoreticalreasontoexpectonedatastructuretobefasterthanotherforexample,Imentionedthatthe i n operatorisfasterfor dictionariesthanforlists,atleastwhenthenumberofelementsislarge. Butoftenyoudontknowaheadoftimewhichimplementationwillbefaster.Oneoptionistoimplementbothofthemandseewhichisbetter.Thisapproach iscalled benchmarking.Apracticalalternativeistochoosethedatastructurethatiseasiesttoimplement,andthenseeifitisfastenoughfortheintended application.Ifso,thereisnoneedtogoon.Ifnot,therearetools,likethe p r o f i l e module,thatcanidentifytheplacesinaprogramthattakethemosttime.
10/24/13
Debugging
Whenyouaredebuggingaprogram,andespeciallyifyouareworkingonahardbug,therearefourthingstotry: reading: Examineyourcode,readitbacktoyourself,andcheckthatitsayswhatyoumeanttosay. running: Experimentbymakingchangesandrunningdifferentversions.Oftenifyoudisplaytherightthingattherightplaceintheprogram,theproblem becomesobvious,butsometimesyouhavetospendsometimetobuildscaffolding. ruminating: Takesometimetothink!Whatkindoferrorisit:syntax,runtime,semantic?Whatinformationcanyougetfromtheerrormessages,orfromtheoutput oftheprogram?Whatkindoferrorcouldcausetheproblemyoureseeing?Whatdidyouchangelast,beforetheproblemappeared? retreating: Atsomepoint,thebestthingtodoisbackoff,undoingrecentchanges,untilyougetbacktoaprogramthatworksandthatyouunderstand.Thenyou canstartingrebuilding. Beginningprogrammerssometimesgetstuckononeoftheseactivitiesandforgettheothers.Eachactivitycomeswithitsownfailuremode. Forexample,readingyourcodemighthelpiftheproblemisatypographicalerror,butnotiftheproblemisaconceptualmisunderstanding.Ifyoudont understandwhatyourprogramdoes,youcanreadit100timesandneverseetheerror,becausetheerrorisinyourhead. Runningexperimentscanhelp,especiallyifyourunsmall,simpletests.Butifyourunexperimentswithoutthinkingorreadingyourcode,youmightfallintoa patternIcallrandomwalkprogramming,whichistheprocessofmakingrandomchangesuntiltheprogramdoestherightthing.Needlesstosay,random walkprogrammingcantakealongtime. Youhavetotaketimetothink.Debuggingislikeanexperimentalscience.Youshouldhaveatleastonehypothesisaboutwhattheproblemis.Iftherearetwo ormorepossibilities,trytothinkofatestthatwouldeliminateoneofthem. Takingabreakhelpswiththethinking.Sodoestalking.Ifyouexplaintheproblemtosomeoneelse(orevenyourself),youwillsometimesfindtheanswer beforeyoufinishaskingthequestion. Buteventhebestdebuggingtechniqueswillfailiftherearetoomanyerrors,orifthecodeyouaretryingtofixistoobigandcomplicated.Sometimesthebest optionistoretreat,simplifyingtheprogramuntilyougettosomethingthatworksandthatyouunderstand.
10/24/13
Glossary
deterministic: Pertainingtoaprogramthatdoesthesamethingeachtimeitruns,giventhesameinputs. pseudorandom: Pertainingtoasequenceofnumbersthatappeartoberandom,butaregeneratedbyadeterministicprogram. defaultvalue: Thevaluegiventoanoptionalparameterifnoargumentisprovided. override: Toreplaceadefaultvaluewithanargument. benchmarking: Theprocessofchoosingbetweendatastructuresbyimplementingalternativesandtestingthemonasampleofthepossibleinputs.
Exercises
Exercise9
Therankofawordisitspositioninalistofwordssortedbyfrequency:themostcommonwordhasrank1,thesecondmostcommonhasrank2,etc. Zipfslawdescribesarelationshipbetweentheranksandfrequenciesofwordsinnaturallanguages1.Specifically,itpredictsthatthefrequency,'f',oftheword withrank'r'is:
Exercise6
Apalindromeisawordthatisspelledthesamebackwardandforward,likenoonandredivider.Recursively,awordisapalindromeifthefirstandlast lettersarethesameandthemiddleisapalindrome.
en.wikibooks.org/wiki/Think_Python/Print_version 139/282
10/24/13
Thefollowingarefunctionsthattakeastringargumentandreturnthefirst,last,andmiddleletters:
d e ff i r s t ( w o r d ) : r e t u r nw o r d [ 0 ] d e fl a s t ( w o r d ) : r e t u r nw o r d [ 1 ] d e fm i d d l e ( w o r d ) : r e t u r nw o r d [ 1 : 1 ]
WellseehowtheyworkinChapter'8'. Typethesefunctionsintoafilenamed'p a l i n d r o m e . p y ' andtestthemout.Whathappensifyoucall'm i d d l e 'withastringwithtwoletters?Oneletter?Whatabouttheemptystring,whichiswritten ' andcontains noletters? Writeafunctioncalled i s _ p a l i n d r o m e thattakes astringargumentandreturns'T r u e 'ifitisapalindromeand'F a l s e 'otherwise.Rememberthatyoucanusethebuiltinfunction'l e n 'tocheckthelengthofa string.
Exercise7
Anumber,'a',isapowerof'b'ifitisdivisibleby'b'and'a/ b'isapowerof'b'.Writeafunctioncalled i s _ p o w e r thattakesparameters'a 'and'b 'andreturns'T r u e ' if'a 'isapowerof'b '.
Exercise8
Thegreatestcommondivisor(GCD)of'a'and'b'isthelargestnumberthatdividesbothofthemwithnoremainder[6]. OnewaytofindtheGCDoftwonumbersisEuclidsalgorithm, whichisbasedontheobservationthatif'r'istheremainderwhen'a'isdividedby'b',then 'gcd(a, b)= gcd(b, r)'.Asabasecase,wecanconsider'gcd(a,0)= a'. Writeafunctioncalled g c d thattakesparameters'a 'and'b 'andreturnstheirgreatestcommondivisor.Ifyouneedhelp,see 'w i k i p e d i a . o r g / w i k i / E u c l i d e a n _ a l g o r i t h m '.
Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.
en.wikibooks.org/wiki/Think_Python/Print_version
140/282
10/24/13
Iteration
Multipleassignment
Asyoumayhavediscovered,itislegaltomakemorethanoneassignmenttothesamevariable.Anewassignmentmakesanexistingvariablerefertoanew value(andstopreferringtotheoldvalue).
b r u c e=5 p r i n tb r u c e , b r u c e=7 p r i n tb r u c e
Theoutputofthisprogramis 57 ,becausethefirsttime b r u c e isprinted,itsvalueis5,andthesecondtime,itsvalueis7.Thecommaattheendofthefirst p r i n t statementsuppressesthenewline,whichiswhybothoutputsappearonthesameline. Hereiswhat multipleassignmentlookslikeinastatediagram: <IMGSRC="book010.png"> Withmultipleassignmentitisespeciallyimportanttodistinguishbetweenanassignmentoperationandastatementofequality.BecausePythonusesthe equalsign(= )forassignment,itistemptingtointerpretastatementlike a=b asastatementofequality.Itisnot! First,equalityisasymmetricrelationandassignmentisnot.Forexample,inmathematics,if a=7then7= a.ButinPython,thestatement a=7 islegaland 7=a isnot. Furthermore,inmathematics,astatementofequalityiseithertrueorfalse,foralltime.If a= bnow,then awillalwaysequal b.InPython,anassignment statementcanmaketwovariablesequal,buttheydonthavetostaythatway:
a=5 b=a a=3
Updatingvariables
Oneofthemostcommonformsofmultipleassignmentisan update,wherethenewvalueofthevariabledependsontheold.
x=x + 1
en.wikibooks.org/wiki/Think_Python/Print_version 141/282
10/24/13
Beforeyoucanupdateavariable,youhaveto initializeit,usuallywithasimpleassignment:
> > >x=0 > > >x=x + 1
Thew h i l e statement
Computersareoftenusedtoautomaterepetitivetasks.Repeatingidenticalorsimilartaskswithoutmakingerrorsissomethingthatcomputersdowelland peopledopoorly. Wehaveseentwoprograms, c o u n t d o w n and p r i n t _ n ,thatuserecursiontoperformrepetition,whichisalsocalled iteration.Becauseiterationissocommon, Pythonprovidesseverallanguagefeaturestomakeiteasier.Oneisthe f o r statementwesawinSection4.2.Wellgetbacktothatlater. Anotheristhe w h i l e statement.Hereisaversionof c o u n t d o w n thatusesa w h i l e statement:
d e fc o u n t d o w n ( n ) : w h i l en>0 : p r i n tn n=n 1 p r i n t' B l a s t o f f ! '
Youcanalmostreadthe w h i l e statementasifitwereEnglish.Itmeans,While n isgreaterthan0,displaythevalueof n andthenreducethevalueof n by1. Whenyougetto0,displaytheword B l a s t o f f ! Moreformally,hereistheflowofexecutionfora w h i l e statement: Evaluatethecondition,yielding T r u e or F a l s e . Iftheconditionisfalse,exitthe w h i l e statementandcontinueexecutionatthenextstatement. Iftheconditionistrue,executethebodyandthengobacktostep1. Thistypeofflowiscalleda loopbecausethethirdsteploopsbackaroundtothetop.
en.wikibooks.org/wiki/Think_Python/Print_version 142/282
10/24/13
#ni se v e n #ni so d d
Theconditionforthisloopis n! =1 ,sotheloopwillcontinueuntil n is 1 ,whichmakestheconditionfalse. Eachtimethroughtheloop,theprogramoutputsthevalueof n andthencheckswhetheritisevenorodd.Ifitiseven, n isdividedby2.Ifitisodd,thevalue of n isreplacedwith n * 3 + 1 .Forexample,iftheargumentpassedto s e q u e n c e is3,theresultingsequenceis3,10,5,16,8,4,2,1. Since n sometimesincreasesandsometimesdecreases,thereisnoobviousproofthat n willeverreach1,orthattheprogramterminates.Forsomeparticular valuesof n ,wecanprovetermination.Forexample,ifthestartingvalueisapoweroftwo,thenthevalueof n willbeeveneachtimethroughtheloopuntilit reaches1.Thepreviousexampleendswithsuchasequence,startingwith16. Thehardquestioniswhetherwecanprovethatthisprogramterminatesfor allpositivevaluesof n .Sofar1,noonehasbeenabletoproveit ordisproveit! Exercise1 Rewritethefunction p r i n t _ n fromSection'5.8'usingiterationinsteadofrecursion.
b r e a k
Sometimesyoudontknowitstimetoendaloopuntilyougethalfwaythroughthebody.Inthatcaseyoucanusethe b r e a k statementtojumpoutofthe loop. Forexample,supposeyouwanttotakeinputfromtheuseruntiltheytype d o n e .Youcouldwrite:
w h i l eT r u e : l i n e=r a w _ i n p u t ( ' >' ) i fl i n e= =' d o n e ' : b r e a k p r i n tl i n e p r i n t' D o n e ! '
en.wikibooks.org/wiki/Think_Python/Print_version 143/282
10/24/13
Squareroots
Loopsareoftenusedinprogramsthatcomputenumericalresultsbystartingwithanapproximateansweranditerativelyimprovingit. Forexample,onewayofcomputingsquarerootsisNewtonsmethod.Supposethatyouwanttoknowthesquarerootof a.Ifyoustartwithalmostany estimate, x,youcancomputeabetterestimatewiththefollowingformula: x+ a/ x 2
y=
Whichisclosertothecorrectanswer(4=2).Ifwerepeattheprocesswiththenewestimate,itgetsevencloser:
> > >x=y > > >y=( x+a / x )/2 > > >p r i n ty 2 . 0 0 6 4 1 0 2 5 6 4 1
Afterafewmoreupdates,theestimateisalmostexact:
en.wikibooks.org/wiki/Think_Python/Print_version
144/282
10/24/13
> > >x=y > > >y=( x+a / x )/2 > > >p r i n ty 2 . 0 0 0 0 1 0 2 4 0 0 3 > > >x=y > > >y=( x+a / x )/2 > > >p r i n ty 2 . 0 0 0 0 0 0 0 0 0 0 3
Ingeneralwedontknowaheadoftimehowmanystepsittakestogettotherightanswer,butweknowwhenwegettherebecausetheestimatestops changing:
> > >x=y > > >y=( x+a / x )/2 > > >p r i n ty 2 . 0 > > >x=y > > >y=( x+a / x )/2 > > >p r i n ty 2 . 0
10/24/13
Algorithms
Newtonsmethodisanexampleofan algorithm:itisamechanicalprocessforsolvingacategoryofproblems(inthiscase,computingsquareroots). Itisnoteasytodefineanalgorithm.Itmighthelptostartwithsomethingthatisnotanalgorithm.Whenyoulearnedtomultiplysingledigitnumbers,you probablymemorizedthemultiplicationtable.Ineffect,youmemorized100specificsolutions.Thatkindofknowledgeisnotalgorithmic. Butifyouwerelazy,youprobablycheatedbylearningafewtricks.Forexample,tofindtheproductof nand9,youcanwrite n1asthefirstdigitand10n astheseconddigit.Thistrickisageneralsolutionformultiplyinganysingledigitnumberby9.Thatsanalgorithm! Similarly,thetechniquesyoulearnedforadditionwithcarrying,subtractionwithborrowing,andlongdivisionareallalgorithms.Oneofthecharacteristicsof algorithmsisthattheydonotrequireanyintelligencetocarryout.Theyaremechanicalprocessesinwhicheachstepfollowsfromthelastaccordingtoa simplesetofrules. Inmyopinion,itisembarrassingthathumansspendsomuchtimeinschoollearningtoexecutealgorithmsthat,quiteliterally,requirenointelligence. Ontheotherhand,theprocessofdesigningalgorithmsisinteresting,intellectuallychallenging,andacentralpartofwhatwecallprogramming. Someofthethingsthatpeopledonaturally,withoutdifficultyorconsciousthought,arethehardesttoexpressalgorithmically.Understandingnatural languageisagoodexample.Wealldoit,butsofarnoonehasbeenabletoexplain howwedoit,atleastnotintheformofanalgorithm.
Debugging
Asyoustartwritingbiggerprograms,youmightfindyourselfspendingmoretimedebugging.Morecodemeansmorechancestomakeanerrorandmore placeforbugstohide. Onewaytocutyourdebuggingtimeisdebuggingbybisection.Forexample,ifthereare100linesinyourprogramandyoucheckthemoneatatime,it wouldtake100steps. Instead,trytobreaktheprobleminhalf.Lookatthemiddleoftheprogram,ornearit,foranintermediatevalueyoucancheck.Adda p r i n t statement(or somethingelsethathasaverifiableeffect)andruntheprogram. Ifthemidpointcheckisincorrect,theproblemmustbeinthefirsthalfoftheprogram.Ifitiscorrect,theproblemisinthesecondhalf. Everytimeyouperformachecklikethis,youhalvethenumberoflinesyouhavetosearch.Aftersixsteps(whichismuchlessthan100),youwouldbedown tooneortwolinesofcode,atleastintheory. Inpracticeitisnotalwaysclearwhatthemiddleoftheprogramisandnotalwayspossibletocheckit.Itdoesntmakesensetocountlinesandfindthe exactmidpoint.Instead,thinkaboutplacesintheprogramwheretheremightbeerrorsandplaceswhereitiseasytoputacheck.Thenchooseaspotwhere youthinkthechancesareaboutthesamethatthebugisbeforeorafterthecheck.
Glossary
en.wikibooks.org/wiki/Think_Python/Print_version 146/282
10/24/13
multipleassignment: Makingmorethanoneassignmenttothesamevariableduringtheexecutionofaprogram. update: Anassignmentwherethenewvalueofthevariabledependsontheold. initialize: Anassignmentthatgivesaninitialvaluetoavariablethatwillbeupdated. increment: Anupdatethatincreasesthevalueofavariable(oftenbyone). decrement: Anupdatethatdecreasesthevalueofavariable. iteration: Repeatedexecutionofasetofstatementsusingeitherarecursivefunctioncalloraloop. infiniteloop: Aloopinwhichtheterminatingconditionisneversatisfied.
Exercises
Exercise3
Totestthesquarerootalgorithminthischapter,youcouldcompareitwith'm a t h . s q r t '.Writeafunctionnamed t e s t _ s q u a r e _ r o o t thatprintsatablelikethis:
' ' 1 . 01 . 0 1 . 0 0 . 0 2 . 01 . 4 1 4 2 1 3 5 6 2 3 71 . 4 1 4 2 1 3 5 6 2 3 72 . 2 2 0 4 4 6 0 4 9 2 5 e 1 6 3 . 01 . 7 3 2 0 5 0 8 0 7 5 71 . 7 3 2 0 5 0 8 0 7 5 70 . 0 4 . 02 . 0 2 . 0 0 . 0 5 . 02 . 2 3 6 0 6 7 9 7 7 5 2 . 2 3 6 0 6 7 9 7 7 5 0 . 0 6 . 02 . 4 4 9 4 8 9 7 4 2 7 82 . 4 4 9 4 8 9 7 4 2 7 80 . 0 7 . 02 . 6 4 5 7 5 1 3 1 1 0 62 . 6 4 5 7 5 1 3 1 1 0 60 . 0 8 . 02 . 8 2 8 4 2 7 1 2 4 7 52 . 8 2 8 4 2 7 1 2 4 7 54 . 4 4 0 8 9 2 0 9 8 5 e 1 6 9 . 03 . 0 3 . 0 0 . 0 ' '
Exercise4
Thebuiltinfunction'e v a l 'takesastringandevaluatesitusingthePythoninterpreter.Forexample:
en.wikibooks.org/wiki/Think_Python/Print_version
147/282
10/24/13
' ' > > >e v a l ( ' 1+2*3 ' ) 7 > > >i m p o r tm a t h > > >e v a l ( ' m a t h . s q r t ( 5 ) ' ) 2 . 2 3 6 0 6 7 9 7 7 4 9 9 7 8 9 8 > > >e v a l ( ' t y p e ( m a t h . p i ) ' ) < t y p e' f l o a t ' > ' '
Exercise5
ThebrilliantmathematicianSrinivasaRamanujanfoundaninfiniteseries2thatcanbeusedtogenerateanumericalapproximationof :
Writeafunctioncalled e s t i m a t e _ p i thatusesthisformulatocomputeandreturnanestimateof''.Itshouldusea'w h i l e 'looptocomputetermsofthe summationuntilthelasttermissmallerthan'1 e 1 5 '(whichisPythonnotationfor'1015). Youcanchecktheresultbycomparingitto'm a t h . p i '. Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / p i . p y '. f=crs where's'and'c'areparametersthatdependonthelanguageandthetext.Ifyoutakethelogarithmofbothsidesofthisequation,youget: log'f='log'cs'log'r Soifyouplot'log'f ' versus'log'r',youshouldgetastraightlinewithslope''s' andintercept'log'c'. Writeaprogramthatreadsatextfromafile,countswordfrequencies,andprintsonelineforeachword,indescendingorderoffrequency,with'log'f ' and 'log'r'.Usethegraphingprogramofyourchoicetoplottheresultsandcheckwhethertheyformastraightline.Canyouestimatethevalueof's'?
Notes
1 See w i k i p e d i a . o r g / w i k i / Z i p f ' s _ l a w
en.wikibooks.org/wiki/Think_Python/Print_version 148/282
10/24/13
Files
Persistence
Mostoftheprogramswehaveseensofararetransientinthesensethattheyrunforashorttimeandproducesomeoutput,butwhentheyend,theirdata disappears.Ifyouruntheprogramagain,itstartswithacleanslate. Otherprogramsare persistent:theyrunforalongtime(orallthetime)theykeepatleastsomeoftheirdatainpermanentstorage(aharddrive,for example)andiftheyshutdownandrestart,theypickupwheretheyleftoff. Examplesofpersistentprogramsareoperatingsystems,whichrunprettymuchwheneveracomputerison,andwebservers,whichrunallthetime,waitingfor requeststocomeinonthenetwork. Oneofthesimplestwaysforprogramstomaintaintheirdataisbyreadingandwritingtextfiles.Wehavealreadyseenprogramsthatreadtextfilesinthis chapterswewillseeprogramsthatwritethem. Analternativeistostorethestateoftheprograminadatabase.InthischapterIwillpresentasimpledatabaseandamodule, p i c k l e ,thatmakesiteasyto storeprogramdata.
Readingandwriting
Atextfileisasequenceofcharactersstoredonapermanentmediumlikeaharddrive,flashmemory,orCDROM.Wesawhowtoopenandreadafilein Section9.1. Towriteafile,youhavetoopenitwithmode ' w ' asasecondparameter:
> > >f o u t=o p e n ( ' o u t p u t . t x t ' ,' w ' ) > > >p r i n tf o u t < o p e nf i l e' o u t p u t . t x t ' ,m o d e' w 'a t0 x b 7 e b 2 4 1 0 >
Again,thefileobjectkeepstrackofwhereitis,soifyoucall w r i t e again,itaddsthenewdatatotheend.
> > >l i n e 2=" t h ee m b l e mo fo u rl a n d . \ n " > > >f o u t . w r i t e ( l i n e 2 )
en.wikibooks.org/wiki/Think_Python/Print_version 149/282
10/24/13
Whenyouaredonewriting,youhavetoclosethefile.
> > >f o u t . c l o s e ( )
Formatoperator
Theargumentof w r i t e hastobeastring,soifwewanttoputothervaluesinafile,wehavetoconvertthemtostrings.Theeasiestwaytodothatiswith s t r :
> > >x=5 2 > > >f . w r i t e ( s t r ( x ) )
Analternativeistousethe formatoperator, % .Whenappliedtointegers, % isthemodulusoperator.Butwhenthefirstoperandisastring, % istheformat operator. Thefirstoperandisthe formatstring,andthesecondoperandisatupleofexpressions.Theresultisastringthatcontainsthevaluesoftheexpressions, formattedaccordingtotheformatstring. Asanexample,the formatsequence ' % d ' meansthatthefirstexpressioninthetupleshouldbeformattedasaninteger(d standsfordecimal):
> > >c a m e l s=4 2 > > >' % d '%c a m e l s ' 4 2 '
Thenumberofelementsinthetuplehastomatchthenumberofformatsequencesinthestring.Also,thetypesoftheelementshavetomatchtheformat sequences:
en.wikibooks.org/wiki/Think_Python/Print_version
150/282
10/24/13
Inthefirstexample,therearentenoughelementsinthesecond,theelementisthewrongtype. Theformatoperatorispowerfulbutdifficulttouse.Youcanreadmoreaboutitat d o c s . p y t h o n . o r g / l i b / t y p e s s e q s t r i n g s . h t m l .
Filenamesandpaths
Filesareorganizedinto directories(alsocalledfolders).Everyrunningprogramhasacurrentdirectory,whichisthedefaultdirectoryformostoperations. Forexample,whenyouopenafileforreading,Pythonlooksforitinthecurrentdirectory. The o s moduleprovidesfunctionsforworkingwithfilesanddirectories(osstandsforoperatingsystem). o s . g e t c w d returnsthenameofthecurrentdirectory:
> > >i m p o r to s > > >c w d=o s . g e t c w d ( ) > > >p r i n tc w d / h o m e / d i n s d a l e
c w d standsforcurrentworkingdirectory.Theresultinthisexampleis / h o m e / d i n s d a l e ,whichisthehomedirectoryofausernamed d i n s d a l e .
Ifitexists, o s . p a t h . i s d i r checkswhetheritsadirectory:
> > >o s . p a t h . i s d i r ( ' m e m o . t x t ' ) F a l s e > > >o s . p a t h . i s d i r ( ' m u s i c ' )
en.wikibooks.org/wiki/Think_Python/Print_version 151/282
10/24/13
T r u e
Similarly, o s . p a t h . i s f i l e checkswhetheritsafile.
o s . l i s t d i r returnsalistofthefiles(andotherdirectories)inthegivendirectory:
Todemonstratethesefunctions,thefollowingexamplewalksthroughadirectory,printsthenamesofallthefiles,andcallsitselfrecursivelyonallthe directories.
d e fw a l k ( d i r ) : f o rn a m ei no s . l i s t d i r ( d i r ) : p a t h=o s . p a t h . j o i n ( d i r ,n a m e ) i fo s . p a t h . i s f i l e ( p a t h ) : p r i n tp a t h e l s e : w a l k ( p a t h )
o s . p a t h . j o i n takesadirectoryandafilenameandjoinsthemintoacompletepath.
Exercise1
Modify'w a l k 'sothatinsteadofprintingthenamesofthefiles,itreturnsalistofnames. Exercise2 The'o s 'moduleprovidesafunctioncalled'w a l k 'thatissimilartothisonebutmoreversatile.Readthedocumentationanduseittoprintthenamesofthefiles inagivendirectoryanditssubdirectories.
Catchingexceptions
Alotofthingscangowrongwhenyoutrytoreadandwritefiles.Ifyoutrytoopenafilethatdoesntexist,yougetan I O E r r o r :
> > >f i n=o p e n ( ' b a d _ f i l e ' ) I O E r r o r :[ E r r n o2 ]N os u c hf i l eo rd i r e c t o r y :' b a d _ f i l e '
Ifyoudonthavepermissiontoaccessafile:
en.wikibooks.org/wiki/Think_Python/Print_version
152/282
10/24/13
> > >f o u t=o p e n ( ' / e t c / p a s s w d ' ,' w ' ) I O E r r o r :[ E r r n o1 3 ]P e r m i s s i o nd e n i e d :' / e t c / p a s s w d '
Andifyoutrytoopenadirectoryforreading,youget
> > >f i n=o p e n ( ' / h o m e ' ) I O E r r o r :[ E r r n o2 1 ]I sad i r e c t o r y
Pythonstartsbyexecutingthe t r y clause.Ifallgoeswell,itskipsthe e x c e p t clauseandproceeds.Ifanexceptionoccurs,itjumpsoutofthe t r y clauseand executesthe e x c e p t clause. Handlinganexceptionwitha t r y statementiscalled catchinganexception.Inthisexample,the e x c e p t clauseprintsanerrormessagethatisnotveryhelpful. Ingeneral,catchinganexceptiongivesyouachancetofixtheproblem,ortryagain,oratleastendtheprogramgracefully.
Databases
A databaseisafilethatisorganizedforstoringdata.Mostdatabasesareorganizedlikeadictionaryinthesensethattheymapfromkeystovalues.The biggestdifferenceisthatthedatabaseisondisk(orotherpermanentstorage),soitpersistsaftertheprogramends. Themodule a n y d b m providesaninterfaceforcreatingandupdatingdatabasefiles.Asanexample,Illcreateadatabasethatcontainscaptionsforimagefiles. Openingadatabaseissimilartoopeningotherfiles:
> > >i m p o r ta n y d b m > > >d b=a n y d b m . o p e n ( ' c a p t i o n s . d b ' ,' c ' )
10/24/13
Whenyouaccessoneoftheitems, a n y d b m readsthefile:
> > >p r i n td b [ ' c l e e s e . p n g ' ] P h o t oo fJ o h nC l e e s e .
Ifyoumakeanotherassignmenttoanexistingkey, a n y d b m replacestheoldvalue:
> > >d b [ ' c l e e s e . p n g ' ]=' P h o t oo fJ o h nC l e e s ed o i n gas i l l yw a l k . ' > > >p r i n td b [ ' c l e e s e . p n g ' ] P h o t oo fJ o h nC l e e s ed o i n gas i l l yw a l k .
Aswithotherfiles,youshouldclosethedatabasewhenyouaredone:
> > >d b . c l o s e ( )
Pickling
Alimitationof a n y d b m isthatthekeysandvalueshavetobestrings.Ifyoutrytouseanyothertype,yougetanerror. The p i c k l e modulecanhelp.Ittranslatesalmostanytypeofobjectintoastringsuitableforstorageinadatabase,andthentranslatesstringsbackintoobjects.
p i c k l e . d u m p s takesanobjectasaparameterandreturnsastringrepresentation(d u m p s isshortfordumpstring):
> > >i m p o r tp i c k l e > > >t=[ 1 ,2 ,3 ] > > >p i c k l e . d u m p s ( t ) ' ( l p 0 \ n I 1 \ n a I 2 \ n a I 3 \ n a . '
10/24/13
> > >s=p i c k l e . d u m p s ( t 1 ) > > >t 2=p i c k l e . l o a d s ( s ) > > >p r i n tt 2 [ 1 ,2 ,3 ]
Althoughthenewobjecthasthesamevalueastheold,itisnot(ingeneral)thesameobject:
> > >t= =t 2 T r u e > > >ti st 2 F a l s e
Pipes
Mostoperatingsystemsprovideacommandlineinterface,alsoknownasa shell .Shellsusuallyprovidecommandstonavigatethefilesystemandlaunch applications.Forexample,inUnix,youcanchangedirectorieswith c d ,displaythecontentsofadirectorywith l s ,andlaunchawebbrowserbytyping(for example) f i r e f o x . AnyprogramthatyoucanlaunchfromtheshellcanalsobelaunchedfromPythonusinga pipe.Apipeisanobjectthatrepresentsarunningprocess. Forexample,theUnixcommand l sl normallydisplaysthecontentsofthecurrentdirectory(inlongformat).Youcanlaunch l s with o s . p o p e n :
> > >c m d=' l sl ' > > >f p=o s . p o p e n ( c m d )
Whenyouaredone,youclosethepipelikeafile:
en.wikibooks.org/wiki/Think_Python/Print_version 155/282
10/24/13
Ifyoureadlinesfrom f p oneatatime,youneverhavetostoretheuncompressedfileinmemoryorondisk.
Writingmodules
AnyfilethatcontainsPythoncodecanbeimportedasamodule.Forexample,supposeyouhaveafilenamed w c . p y withthefollowingcode:
d e fl i n e c o u n t ( f i l e n a m e ) : c o u n t=0 f o rl i n ei no p e n ( f i l e n a m e ) : c o u n t+ =1 r e t u r nc o u n t p r i n tl i n e c o u n t ( ' w c . p y ' )
Ifyourunthisprogram,itreadsitselfandprintsthenumberoflinesinthefile,whichis7.Youcanalsoimportitlikethis:
> > >i m p o r tw c 7
Nowyouhaveamoduleobject w c :
> > >p r i n tw c < m o d u l e' w c 'f r o m' w c . p y ' >
Thatprovidesafunctioncalled l i n e c o u n t :
en.wikibooks.org/wiki/Think_Python/Print_version
156/282
10/24/13
isexecuted.Otherwise,ifthemoduleisbeingimported,thetestcodeisskipped. Exercise4 Typethisexampleintoafilenamed'w c . p y 'andrunitasascript.ThenrunthePythoninterpreterand'i m p o r tw c '.Whatisthevalueof _ _ n a m e _ _ whenthemodule isbeingimported? Warning:Ifyouimportamodulethathasalreadybeenimported, Pythondoesnothing.Itdoesnotrereadthefile,evenifithaschanged. Ifyouwanttoreloadamodule,youcanusethebuiltinfunction'r e l o a d ',butitcanbetricky,sothesafestthingtodoisrestarttheinterpreterandthenimport themoduleagain.
Debugging
Whenyouarereadingandwritingfiles,youmightrunintoproblemswithwhitespace.Theseerrorscanbehardtodebugbecausespaces,tabsandnewlines arenormallyinvisible:
> > >s=' 12 \ t3 \ n4 ' > > >p r i n ts 12 3 4
Thiscanbehelpfulfordebugging.
en.wikibooks.org/wiki/Think_Python/Print_version 157/282
10/24/13
Glossary
persistent: Pertainingtoaprogramthatrunsindefinitelyandkeepsatleastsomeofitsdatainpermanentstorage. formatoperator: Anoperator, % ,thattakesaformatstringandatupleandgeneratesastringthatincludestheelementsofthetupleformattedasspecifiedbytheformat string. formatstring: Astring,usedwiththeformatoperator,thatcontainsformatsequences. formatsequence: Asequenceofcharactersinaformatstring,like % d ,thatspecifieshowavalueshouldbeformatted. textfile: Asequenceofcharactersstoredinpermanentstoragelikeaharddrive. directory: Anamedcollectionoffiles,alsocalledafolder. path: Astringthatidentifiesafile. relativepath: Apaththatstartsfromthecurrentdirectory. absolutepath: Apaththatstartsfromthetopmostdirectoryinthefilesystem. catch: Topreventanexceptionfromterminatingaprogramusingthe t r y and e x c e p t statements. database: Afilewhosecontentsareorganizedlikeadictionarywithkeysthatcorrespondtovalues.
Exercises
Exercise5 The'u r l l i b 'moduleprovidesmethodsformanipulatingURLsanddownloadinginformationfromtheweb.Thefollowingexampledownloadsandprintsasecret messagefrom't h i n k p y t h o n . c o m ':
en.wikibooks.org/wiki/Think_Python/Print_version 158/282
10/24/13
Runthiscodeandfollowtheinstructionsyouseethere. Exercise6 InalargecollectionofMP3files,theremaybemorethanonecopyofthesamesong,storedindifferentdirectoriesorwithdifferentfilenames.Thegoalof thisexerciseistosearchfortheseduplicates. Writeaprogramthatsearchesadirectoryandallofits subdirectories,recursively,andreturnsalistofcompletepathsforallfileswithagivensuffix(like'. m p 3 ').Hint:'o s . p a t h 'providesseveralusefulfunctionsfor manipulatingfileandpathnames. Torecognizeduplicates,youcanuseahashfunctionthat readsthefileandgeneratesashortsummaryofthecontents.Forexample,MD5(MessageDigestalgorithm5)takesanarbitrarilylongmessageandreturns a128bitchecksum.Theprobabilityisverysmallthattwofileswithdifferentcontentswillreturnthesamechecksum. YoucanreadaboutMD5at 'w i k i p e d i a . o r g / w i k i / M d 5 '.OnaUnixsystemyoucanusetheprogram'm d 5 s u m 'andapipetocomputechecksumsfromPython. Exercise7 ' TheInternetMovieDatabase(IMDb)isanonlinecollectionof informationaboutmovies.Theirdatabaseisavailableinplaintextformat,soitisreasonably easytoreadfromPython.Forthisexercise,thefilesyouneedare'a c t o r s . l i s t . g z 'and'a c t r e s s e s . l i s t . g z 'youcandownloadthemfrom 'w w w . i m d b . c o m / i n t e r f a c e s # p l a i n '. ' Ihavewrittenaprogramthatparsesthesefilesandsplitsthemintoactornames,movietitles,etc.Youcandownloaditfrom't h i n k p y t h o n . c o m / c o d e / i m d b . p y '. Ifyourun'i m d b . p y 'asascript,itreads'a c t o r s . l i s t . g z 'andprintsoneactormoviepairperline.Or,ifyou'i m p o r t i m d b ' youcanusethefunction p r o c e s s _ f i l e to, well, processthefile.Theargumentsareafilename,afunctionobjectandanoptionalnumberoflinestoprocess.Hereisanexample:
' ' i m p o r ti m d b d e fp r i n t _ i n f o ( a c t o r ,d a t e ,t i t l e ,r o l e ) : p r i n ta c t o r ,d a t e ,t i t l e ,r o l e i m d b . p r o c e s s _ f i l e ( ' a c t o r s . l i s t . g z ' ,p r i n t _ i n f o )
en.wikibooks.org/wiki/Think_Python/Print_version 159/282
10/24/13
' '
Whenyoucall p r o c e s s _ f i l e ,itopens'f i l e n a m e ',readsthecontents,andcalls p r i n t _ i n f o onceforeachlineinthefile. p r i n t _ i n f o takesanactor,date,movietitleand roleasargumentsandprintsthem. Writeaprogramthatreads'a c t o r s . l i s t . g z 'and'a c t r e s s e s . l i s t . g z 'anduses's h e l v e 'tobuildadatabase thatmapsfromeachactortoalistofhisorherfilms. Twoactorsarecostarsiftheyhavebeeninatleastone movietogether.Processthedatabaseyoubuiltinthepreviousstepandbuildaseconddatabasethatmapsfromeachactortoalistofhisorhercostars. WriteaprogramthatcanplaytheSixDegreesofKevin Bacon,whichyoucanreadaboutat'w i k i p e d i a . o r g / w i k i / S i x _ D e g r e e s _ o f _ K e v i n _ B a c o n '.Thisproblemischallengingbecauseitrequiresyoutofindtheshortestpathin agraph.Youcanreadaboutshortestpathalgorithmsat'w i k i p e d i a . o r g / w i k i / S h o r t e s t _ p a t h _ p r o b l e m '.
Classesandobjects
Userdefinedtypes
WehaveusedmanyofPythonsbuiltintypesnowwearegoingtodefineanewtype.Asanexample,wewillcreateatypecalled P o i n t thatrepresentsapoint intwodimensionalspace. Inmathematicalnotation,pointsareoftenwritteninparentheseswithacommaseparatingthecoordinates.Forexample,(0,0)representstheorigin,and(x, y)representsthepoint xunitstotherightand yunitsupfromtheorigin. ThereareseveralwayswemightrepresentpointsinPython: Wecouldstorethecoordinatesseparatelyintwovariables, x and y . Wecouldstorethecoordinatesaselementsinalistortuple. Wecouldcreateanewtypetorepresentpointsasobjects. Creatinganewtypeis(alittle)morecomplicatedthantheotheroptions,butithasadvantagesthatwillbeapparentsoon. Auserdefinedtypeisalsocalleda class.Aclassdefinitionlookslikethis:
c l a s sP o i n t ( o b j e c t ) : " " " r e p r e s e n t sap o i n ti n2 Ds p a c e " " "
10/24/13
Attributes
Youcanassignvaluestoaninstanceusingdotnotation:
> > >b l a n k . x=3 . 0 > > >b l a n k . y=4 . 0
Thissyntaxissimilartothesyntaxforselectingavariablefromamodule,suchas m a t h . p i or s t r i n g . w h i t e s p a c e .Inthiscase,though,weareassigningvaluesto namedelementsofanobject.Theseelementsarecalled attributes. Asanoun,ATtributeispronouncedwithemphasisonthefirstsyllable,asopposedtoaTRIBute,whichisaverb. Thefollowingdiagramshowstheresultoftheseassignments.Astatediagramthatshowsanobjectanditsattributesiscalledan objectdiagram: <IMGSRC="book022.png"> Thevariable b l a n k referstoaPointobject,whichcontainstwoattributes.Eachattributereferstoafloatingpointnumber. Youcanreadthevalueofanattributeusingthesamesyntax:
> > >p r i n tb l a n k . y
en.wikibooks.org/wiki/Think_Python/Print_version 161/282
10/24/13
Youcanpassaninstanceasanargumentintheusualway.Forexample:
d e fp r i n t _ p o i n t ( p ) : p r i n t' ( % g ,% g ) '%( p . x ,p . y )
p r i n t _ p o i n t takesapointasanargumentanddisplaysitinmathematicalnotation.Toinvokeit,youcanpass b l a n k asanargument:
Exercise1
Writeafunctioncalled'd i s t a n c e 'thatittakestwoPointsasargumentsandreturnsthedistancebetweenthem.
Rectangles
Sometimesitisobviouswhattheattributesofanobjectshouldbe,butothertimesyouhavetomakedecisions.Forexample,imagineyouaredesigninga classtorepresentrectangles.Whatattributeswouldyouusetospecifythelocationandsizeofarectangle?Youcanignoreangletokeepthingssimple, assumethattherectangleiseitherverticalorhorizontal. Thereareatleasttwopossibilities: Youcouldspecifyonecorneroftherectangle(orthecenter),thewidth,andtheheight.
en.wikibooks.org/wiki/Think_Python/Print_version 162/282
10/24/13
Instancesasreturnvalues
Functionscanreturninstances.Forexample, f i n d _ c e n t e r takesa R e c t a n g l e asanargumentandreturnsa P o i n t thatcontainsthecoordinatesofthecenterofthe R e c t a n g l e :
d e ff i n d _ c e n t e r ( b o x ) : p=P o i n t ( ) p . x=b o x . c o r n e r . x+b o x . w i d t h / 2 . 0 p . y=b o x . c o r n e r . y+b o x . h e i g h t / 2 . 0 r e t u r np
Hereisanexamplethatpasses b o x asanargumentandassignstheresultingPointto c e n t e r :
en.wikibooks.org/wiki/Think_Python/Print_version 163/282
10/24/13
Objectsaremutable
Youcanchangethestateofanobjectbymakinganassignmenttooneofitsattributes.Forexample,tochangethesizeofarectanglewithoutchangingits position,youcanmodifythevaluesof w i d t h and h e i g h t :
b o x . w i d t h=b o x . w i d t h+5 0 b o x . h e i g h t=b o x . h e i g h t+1 0 0
Hereisanexamplethatdemonstratestheeffect:
> > >p r i n tb o x . w i d t h 1 0 0 . 0 > > >p r i n tb o x . h e i g h t 2 0 0 . 0 > > >g r o w _ r e c t a n g l e ( b o x ,5 0 ,1 0 0 ) > > >p r i n tb o x . w i d t h 1 5 0 . 0 > > >p r i n tb o x . h e i g h t 3 0 0 . 0
Exercise2
Writeafunctionnamed m o v e _ r e c t a n g l e thattakesaRectangleandtwonumbersnamed'd x 'and'd y '.Itshouldchangethelocationoftherectanglebyadding'd x ' tothe'x 'coordinateof'c o r n e r 'andadding'd y 'tothe'y 'coordinateof'c o r n e r '.
Copying
Aliasingcanmakeaprogramdifficulttoreadbecausechangesinoneplacemighthaveunexpectedeffectsinanotherplace.Itishardtokeeptrackofallthe en.wikibooks.org/wiki/Think_Python/Print_version 164/282
10/24/13
> > >p r i n t _ p o i n t ( p 1 ) ( 3 . 0 ,4 . 0 ) > > >p r i n t _ p o i n t ( p 2 ) ( 3 . 0 ,4 . 0 ) > > >p 1i sp 2 F a l s e > > >p 1= =p 2 F a l s e
The i s operatorindicatesthat p 1 and p 2 arenotthesameobject,whichiswhatweexpected.Butyoumighthaveexpected = = toyield T r u e becausethesepoints containthesamedata.Inthatcase,youwillbedisappointedtolearnthatforinstances,thedefaultbehaviorofthe = = operatoristhesameasthe i s operator itchecksobjectidentity,notobjectequivalence.Thisbehaviorcanbechangedwellseehowlater. Ifyouuse c o p y . c o p y toduplicateaRectangle,youwillfindthatitcopiestheRectangleobjectbutnottheembeddedPoint.
> > >b o x 2=c o p y . c o p y ( b o x ) > > >b o x 2i sb o x F a l s e > > >b o x 2 . c o r n e ri sb o x . c o r n e r T r u e
10/24/13
Exercise3
Writeaversionof m o v e _ r e c t a n g l e thatcreatesandreturnsanewRectangleinsteadofmodifyingtheoldone.
Debugging
Whenyoustartworkingwithobjects,youarelikelytoencountersomenewexceptions.Ifyoutrytoaccessanattributethatdoesntexist,yougetan A t t r i b u t e E r r o r :
> > >p=P o i n t ( ) > > >p r i n tp . z A t t r i b u t e E r r o r :P o i n ti n s t a n c eh a sn oa t t r i b u t e' z '
Ifyouarenotsurewhattypeanobjectis,youcanask:
> > >t y p e ( p ) < t y p e' _ _ m a i n _ _ . P o i n t ' >
Ifyouarenotsurewhetheranobjecthasaparticularattribute,youcanusethebuiltinfunction h a s a t t r :
> > >h a s a t t r ( p ,' x ' ) T r u e > > >h a s a t t r ( p ,' z ' ) F a l s e
Thefirstargumentcanbeanyobjectthesecondargumentisa stringthatcontainsthenameoftheattribute.
Glossary
en.wikibooks.org/wiki/Think_Python/Print_version 166/282
10/24/13
class: Auserdefinedtype.Aclassdefinitioncreatesanewclassobject. classobject: Anobjectthatcontainsinformationaboutauserdefinedtype.Theclassobjectcanbeusedtocreateinstancesofthetype. instance: Anobjectthatbelongstoaclass. attribute: Oneofthenamedvaluesassociatedwithanobject. embedded(object): Anobjectthatisstoredasanattributeofanotherobject. shallowcopy: Tocopythecontentsofanobject,includinganyreferencestoembeddedobjectsimplementedbythe c o p y functioninthe c o p y module. deepcopy: Tocopythecontentsofanobjectaswellasanyembeddedobjects,andanyobjectsembeddedinthem,andsoonimplementedbythe d e e p c o p y functioninthe c o p y module. objectdiagram: Adiagramthatshowsobjects,theirattributes,andthevaluesoftheattributes.
Exercises
Exercise4
W o r l d . p y '',whichispartofSwampy(seeChapter'4'),containsaclassdefinitionforauserdefinedtypecalled'W o r l d '.Ifyourunthiscode:
10/24/13
theupperrightcorner. Youcandrawacirclelikethis:
' ' c a n v a s . c i r c l e ( [ 2 5 , 0 ] ,7 0 ,o u t l i n e = N o n e ,f i l l = ' r e d ' ) ' '
Thefirstparameteristhecoordinatepairforthecenterofthecirclethesecondparameteristheradius. Ifyouaddthislinetotheprogram, theresultshouldresemblethenationalflagofBangladesh(see'w i k i p e d i a . o r g / w i k i / G a l l e r y _ o f _ s o v e r e i g n s t a t e _ f l a g s '). Writeafunctioncalled d r a w _ r e c t a n g l e thattakesa CanvasandaRectangleasargumentsanddrawsarepresentationoftheRectangleontheCanvas. Addanattributenamed'c o l o r 'toyourRectangleobjectsand modify d r a w _ r e c t a n g l e sothatitusesthecolorattributeasthefillcolor. Writeafunctioncalled d r a w _ p o i n t thattakesa CanvasandaPointasargumentsanddrawsarepresentationofthePointontheCanvas. DefineanewclasscalledCirclewithappropriateattributesand instantiateafewCircleobjects.Writeafunctioncalled d r a w _ c i r c l e thatdrawscirclesonthecanvas. WriteaprogramthatdrawsthenationalflagofoftheCzechRepublic(http://en.wikipedia.org/wiki/File:Flag_of_the_Czech_Republic.svg). Hint:youcandrawapolygonlikethis:
' ' p o i n t s=[ [ 1 5 0 , 1 0 0 ] ,[ 1 5 0 ,1 0 0 ] ,[ 1 5 0 ,1 0 0 ] ] c a n v a s . p o l y g o n ( p o i n t s ,f i l l = ' b l u e ' ) ' '
Classesandfunctions
en.wikibooks.org/wiki/Think_Python/Print_version 168/282
10/24/13
Time
Asanotherexampleofauserdefinedtype,we'lldefineaclasscalled T i m e thatrecordsthetimeofday.Theclassdefinitionlookslikethis:
c l a s sT i m e ( o b j e c t ) : " " " r e p r e s e n t st h et i m eo fd a y . a t t r i b u t e s :h o u r ,m i n u t e ,s e c o n d " " "
Wecancreateanew T i m e objectandassignattributesforhours,minutes,andseconds:
t i m e=T i m e ( ) t i m e . h o u r=1 1 t i m e . m i n u t e=5 9 t i m e . s e c o n d=3 0
Thestatediagramforthe T i m e objectlookslikethis:
<IMGSRC="book025.png">
Exercise1
Writeafunctioncalled p r i n t _ t i m e thattakesaTimeobjectandprintsitintheform h o u r : m i n u t e : s e c o n d . Hint:theformatsequence % . 2 d printsanintegerusingatleasttwodigits,includingaleadingzeroifnecessary.
Exercise2
Writeabooleanfunctioncalled i s _ a f t e r thattakestwoTimeobjects, t 1 and t 2 ,andreturns T r u e if t 1 follows t 2 chronologicallyand F a l s e otherwise. Challenge:don'tusean i f statement.
Purefunctions
Inthenextfewsections,wellwritetwofunctionsthataddtimevalues.Theydemonstratetwokindsoffunctions:purefunctionsandmodifiers.Theyalso demonstrateadevelopmentplanIllcall prototypeandpatch,whichisawayoftacklingacomplexproblembystartingwithasimpleprototypeand incrementallydealingwiththecomplications. Hereisasimpleprototypeof a d d _ t i m e :
d e fa d d _ t i m e ( t 1 ,t 2 ) :
en.wikibooks.org/wiki/Think_Python/Print_version 169/282
10/24/13
Thefunctioncreatesanew T i m e object,initializesitsattributes,andreturnsareferencetothenewobject.Thisiscalleda purefunctionbecauseitdoesnot modifyanyoftheobjectspassedtoitasargumentsandithasnoeffect,likedisplayingavalueorgettinguserinput,otherthanreturningavalue. Totestthisfunction,IllcreatetwoTimeobjects: s t a r t containsthestarttimeofamovie,like MontyPythonandtheHolyGrail,and d u r a t i o n containstherun timeofthemovie, whichisonehour35minutes.
a d d _ t i m e figuresoutwhenthemoviewillbedone.
> > >s t a r t=T i m e ( ) > > >s t a r t . h o u r=9 > > >s t a r t . m i n u t e=4 5 > > >s t a r t . s e c o n d= 0 > > >d u r a t i o n=T i m e ( ) > > >d u r a t i o n . h o u r=1 > > >d u r a t i o n . m i n u t e=3 5 > > >d u r a t i o n . s e c o n d=0 > > >d o n e=a d d _ t i m e ( s t a r t ,d u r a t i o n ) > > >p r i n t _ t i m e ( d o n e ) 1 0 : 8 0 : 0 0
10/24/13
r e t u r ns u m
Althoughthisfunctioniscorrect,itisstartingtogetbig.Wewillseeashorteralternativelater.
Modifiers
Sometimesitisusefulforafunctiontomodifytheobjectsitgetsasparameters.Inthatcase,thechangesarevisibletothecaller.Functionsthatworkthis wayarecalled modifiers.
i n c r e m e n t ,whichaddsagivennumberofsecondstoa T i m e object,canbewrittennaturallyasamodifier.Hereisaroughdraft:
Thefirstlineperformsthebasicoperationtheremainderdealswiththespecialcaseswesawbefore. Isthisfunctioncorrect?Whathappensiftheparameter s e c o n d s ismuchgreaterthansixty? Inthatcase,itisnotenoughtocarryoncewehavetokeepdoingituntil t i m e . s e c o n d islessthansixty.Onesolutionistoreplacethe i f statementswith w h i l e statements.Thatwouldmakethefunctioncorrect,butnotveryefficient. Exercise3 Writeacorrectversionof'i n c r e m e n t 'thatdoesntcontainanyloops. Anythingthatcanbedonewithmodifierscanalsobedonewithpurefunctions.Infact,someprogramminglanguagesonlyallowpurefunctions.Thereissome evidencethatprogramsthatusepurefunctionsarefastertodevelopandlesserrorpronethanprogramsthatusemodifiers.Butmodifiersareconvenientat times,andfunctionalprogramstendtobelessefficient. Ingeneral,Irecommendthatyouwritepurefunctionswheneveritisreasonableandresorttomodifiersonlyifthereisacompellingadvantage.Thisapproach mightbecalleda functional programmingstyle. Exercise4 Writeapureversionof'i n c r e m e n t 'thatcreatesandreturnsanewTimeobjectratherthanmodifyingtheparameter.
en.wikibooks.org/wiki/Think_Python/Print_version
171/282
10/24/13
Prototypingversusplanning
ThedevelopmentplanIamdemonstratingiscalledprototypeandpatch.Foreachfunction,Iwroteaprototypethatperformedthebasiccalculationandthen testedit,patchingerrorsalongtheway. Thisapproachcanbeeffective,especiallyifyoudontyethaveadeepunderstandingoftheproblem.Butincrementalcorrectionscangeneratecodethatis unnecessarilycomplicatedsinceitdealswithmanyspecialcasesandunreliablesinceitishardtoknowifyouhavefoundalltheerrors. Analternativeis planneddevelopment,inwhichhighlevelinsightintotheproblemcanmaketheprogrammingmucheasier.Inthiscase,theinsightisthata Timeobjectisreallyathreedigitnumberinbase60(see w i k i p e d i a . o r g / w i k i / S e x a g e s i m a l )!The s e c o n d attributeistheonescolumn,the m i n u t e attributeisthe sixtiescolumn,andthe h o u r attributeisthethirtysixhundredscolumn. Whenwewrote a d d _ t i m e and i n c r e m e n t ,wewereeffectivelydoingadditioninbase60,whichiswhywehadtocarryfromonecolumntothenext. ThisobservationsuggestsanotherapproachtothewholeproblemwecanconvertTimeobjectstointegersandtakeadvantageofthefactthatthecomputer knowshowtodointegerarithmetic. HereisafunctionthatconvertsTimestointegers:
d e ft i m e _ t o _ i n t ( t i m e ) : m i n u t e s=t i m e . h o u r*6 0+t i m e . m i n u t e s e c o n d s=m i n u t e s*6 0+t i m e . s e c o n d r e t u r ns e c o n d s
Thisversionisshorterthantheoriginal,andeasiertoverify.
en.wikibooks.org/wiki/Think_Python/Print_version 172/282
10/24/13
Exercise5 Rewrite'i n c r e m e n t 'using t i m e _ t o _ i n t and i n t _ t o _ t i m e . Insomeways,convertingfrombase60tobase10andbackisharderthanjustdealingwithtimes.Baseconversionismoreabstractourintuitionfordealing withtimevaluesisbetter. Butifwehavetheinsighttotreattimesasbase60numbersandmaketheinvestmentofwritingtheconversionfunctions(t i m e _ t o _ i n t and i n t _ t o _ t i m e ),wegeta programthatisshorter,easiertoreadanddebug,andmorereliable. Itisalsoeasiertoaddfeatureslater.Forexample,imaginesubtractingtwoTimestofindthedurationbetweenthem.Thenaveapproachwouldbeto implementsubtractionwithborrowing.Usingtheconversionfunctionswouldbeeasierandmorelikelytobecorrect. Ironically,sometimesmakingaproblemharder(ormoregeneral)makesiteasier(becausetherearefewerspecialcasesandfeweropportunitiesforerror).
Debugging
ATimeobjectiswellformedifthevaluesof m i n u t e s and s e c o n d s arebetween0and60(including0butnot60)andif h o u r s ispositive. h o u r s and m i n u t e s shouldbe integralvalues,butwemightallow s e c o n d s tohaveafractionpart. Thesekindofrequirementsarecalled invariantsbecausetheyshouldalwaysbetrue.Toputitadifferentway,iftheyarenottrue,thensomethinghasgone wrong. Writingcodetocheckyourinvariantscanhelpyoudetecterrorsandfindtheircauses.Forexample,youmighthaveafunctionlike v a l i d _ t i m e thattakesaTime objectandreturns F a l s e ifitviolatesaninvariant:
d e fv a l i d _ t i m e ( t i m e ) : i ft i m e . h o u r s<0o rt i m e . m i n u t e s<0o rt i m e . s e c o n d s<0 : r e t u r nF a l s e i ft i m e . m i n u t e s> =6 0o rt i m e . s e c o n d s> =6 0 : r e t u r nF a l s e r e t u r nT r u e
Thenatthebeginningofeachfunctionyoucouldchecktheargumentstomakesuretheyarevalid:
Oryoucouldusean a s s e r t statement,whichchecksagiveninvariantandraisesanexceptionifitfails:
en.wikibooks.org/wiki/Think_Python/Print_version 173/282
10/24/13
d e fa d d _ t i m e ( t 1 ,t 2 ) : a s s e r tv a l i d _ t i m e ( t 1 )a n dv a l i d _ t i m e ( t 2 ) s e c o n d s=t i m e _ t o _ i n t ( t 1 )+t i m e _ t o _ i n t ( t 2 ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s )
a s s e r t statementsareusefulbecausetheydistinguishcodethatdealswithnormalconditionsfromcodethatchecksforerrors.
Glossary
prototypeandpatch: Adevelopmentplanthatinvolveswritingaroughdraftofaprogram,testing,andcorrectingerrorsastheyarefound. planneddevelopment: Adevelopmentplanthatinvolveshighlevelinsightintotheproblemandmoreplanningthanincrementaldevelopmentorprototypedevelopment. purefunction: Afunctionthatdoesnotmodifyanyoftheobjectsitreceivesasarguments.Mostpurefunctionsarefruitful. modifier: Afunctionthatchangesoneormoreoftheobjectsitreceivesasarguments.Mostmodifiersarefruitless. functionalprogrammingstyle: Astyleofprogramdesigninwhichthemajorityoffunctionsarepure. invariant: Aconditionthatshouldalwaysbetrueduringtheexecutionofaprogram.
Exercises
Exercise6
Writeafunctioncalled m u l _ t i m e thattakesaTimeobjectandanumberandreturnsanewTimeobjectthatcontainstheproductoftheoriginalTimeandthe number. Thenuse m u l _ t i m e towriteafunctionthattakesaTimeobjectthatrepresentsthefinishingtimeinarace,andanumberthatrepresentsthedistance, andreturnsaTimeobjectthatrepresentstheaveragepace(timepermile).
Exercise7
WriteaclassdefinitionforaDateobjectthathasattributes'd a y ','m o n t h 'and'y e a r '.Writeafunctioncalled i n c r e m e n t _ d a t e thattakesaDateobject,'d a t e 'andan integer,'n ',andreturnsanewDateobjectthatrepresentstheday'n 'daysafter'd a t e '.Hint:ThirtydayshathSeptember...Challenge:doesyourfunctiondeal withleapyearscorrectly?See''w i k i p e d i a . o r g / w i k i / L e a p _ y e a r
Exercise8
en.wikibooks.org/wiki/Think_Python/Print_version 174/282
10/24/13
Classesandmethods
Objectorientedfeatures
Pythonisan objectorientedprogramminglanguage,whichmeansthatitprovidesfeaturesthatsupportobjectorientedprogramming. Itisnoteasytodefineobjectorientedprogramming,butwehavealreadyseensomeofitscharacteristics: Programsaremadeupofobjectdefinitionsandfunction definitions,andmostofthecomputationisexpressedintermsofoperationsonobjects. Eachobjectdefinitioncorrespondstosomeobjectorconcept intherealworld,andthefunctionsthatoperateonthatobjectcorrespondtothewaysrealworldobjectsinteract. Forexample,the T i m e classdefinedinChapter16correspondstothewaypeoplerecordthetimeofday,andthefunctionswedefinedcorrespondtothekinds ofthingspeopledowithtimes.Similarly,the P o i n t and R e c t a n g l e classescorrespondtothemathematicalconceptsofapointandarectangle. Sofar,wehavenottakenadvantageofthefeaturesPythonprovidestosupportobjectorientedprogramming.Thesefeaturesarenotstrictlynecessarymost ofthemprovidealternativesyntaxforthingswehavealreadydone.Butinmanycases,thealternativeismoreconciseandmoreaccuratelyconveysthe structureoftheprogram. Forexample,inthe T i m e program,thereisnoobviousconnectionbetweentheclassdefinitionandthefunctiondefinitionsthatfollow.Withsomeexamination, itisapparentthateveryfunctiontakesatleastone T i m e objectasanargument. Thisobservationisthemotivationfor methodsamethodisafunctionthatisassociatedwithaparticularclass.Wehaveseenmethodsforstrings,lists, dictionariesandtuples.Inthischapter,wewilldefinemethodsforuserdefinedtypes. Methodsaresemanticallythesameasfunctions,buttherearetwosyntacticdifferences: Methodsaredefinedinsideaclassdefinitioninordertomaketherelationshipbetweentheclassandthemethodexplicit. Thesyntaxforinvokingamethodisdifferentfromthesyntaxforcallingafunction. Inthenextfewsections,wewilltakethefunctionsfromtheprevioustwochaptersandtransformthemintomethods.Thistransformationispurelymechanical youcandoitsimplybyfollowingasequenceofsteps.Ifyouarecomfortableconvertingfromoneformtoanother,youwillbeabletochoosethebestformfor whateveryouaredoing.
en.wikibooks.org/wiki/Think_Python/Print_version 175/282
10/24/13
Printingobjects
InChapter16,wedefinedaclassnamed T i m e andinExercise16.1,youwroteafunctionnamed p r i n t _ t i m e :
c l a s sT i m e ( o b j e c t ) : " " " r e p r e s e n t st h et i m eo fd a y . a t t r i b u t e s :h o u r ,m i n u t e ,s e c o n d " " " d e fp r i n t _ t i m e ( t i m e ) : p r i n t' % . 2 d : % . 2 d : % . 2 d '%( t i m e . h o u r ,t i m e . m i n u t e ,t i m e . s e c o n d )
Tocallthisfunction,youhavetopassa T i m e objectasanargument:
> > >s t a r t=T i m e ( ) > > >s t a r t . h o u r=9 > > >s t a r t . m i n u t e=4 5 > > >s t a r t . s e c o n d=0 0 > > >p r i n t _ t i m e ( s t a r t ) 0 9 : 4 5 : 0 0
Tomake p r i n t _ t i m e amethod,allwehavetodoismovethefunctiondefinitioninsidetheclassdefinition.Noticethechangeinindentation.
c l a s sT i m e ( o b j e c t ) : d e fp r i n t _ t i m e ( t i m e ) : p r i n t' % . 2 d : % . 2 d : % . 2 d '%( t i m e . h o u r ,t i m e . m i n u t e ,t i m e . s e c o n d )
Nowtherearetwowaystocall p r i n t _ t i m e .Thefirst(andlesscommon)wayistousefunctionsyntax:
> > >T i m e . p r i n t _ t i m e ( s t a r t ) 0 9 : 4 5 : 0 0
10/24/13
Thereasonforthisconventionisanimplicitmetaphor: Thesyntaxforafunctioncall, p r i n t _ t i m e ( s t a r t ) , suggeststhatthefunctionistheactiveagent.Itsayssomethinglike,Hey p r i n t _ t i m e !Heresanobjectforyoutoprint. Inobjectorientedprogramming,theobjectsaretheactive agents.Amethodinvocationlike s t a r t . p r i n t _ t i m e ( ) saysHey s t a r t !Pleaseprintyourself. Thischangeinperspectivemightbemorepolite,butitisnotobviousthatitisuseful.Intheexampleswehaveseensofar,itmaynotbe.Butsometimes shiftingresponsibilityfromthefunctionsontotheobjectsmakesitpossibletowritemoreversatilefunctions,andmakesiteasiertomaintainandreusecode.
Exercise1
Rewrite t i m e _ t o _ i n t (fromSection'16.4')asamethod.Itisprobablynotappropriatetorewrite i n t _ t o _ t i m e asamethoditsnotclearwhatobjectyouwould invokeiton!
Anotherexample
Heresaversionof i n c r e m e n t (fromSection16.3)rewrittenasamethod:
#i n s i d ec l a s sT i m e : d e fi n c r e m e n t ( s e l f ,s e c o n d s ) : s e c o n d s+ =s e l f . t i m e _ t o _ i n t ( ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s )
10/24/13
Theerrormessageisinitiallyconfusing,becausethereareonlytwoargumentsinparentheses.Butthesubjectisalsoconsideredanargument,soalltogether thatsthree.
Amorecomplicatedexample
i s _ a f t e r (fromExercise16.2)isslightlymorecomplicatedbecauseittakestwoTimeobjectsasparameters.Inthiscaseitisconventionaltonamethefirst
parameter s e l f andthesecondparameter o t h e r :
#i n s i d ec l a s sT i m e : d e fi s _ a f t e r ( s e l f ,o t h e r ) : r e t u r ns e l f . t i m e _ t o _ i n t ( )>o t h e r . t i m e _ t o _ i n t ( )
Tousethismethod,youhavetoinvokeitononeobjectandpasstheotherasanargument:
> > >e n d . i s _ a f t e r ( s t a r t ) T r u e
OnenicethingaboutthissyntaxisthatitalmostreadslikeEnglish:endisafterstart?
Theinitmethod
Theinitmethod(shortforinitialization)isaspecialmethodthatgetsinvokedwhenanobjectisinstantiated.Itsfullnameis _ _ i n i t _ _ (twounderscore characters,followedby i n i t ,andthentwomoreunderscores).Aninitmethodforthe T i m e classmightlooklikethis:
#i n s i d ec l a s sT i m e : d e f_ _ i n i t _ _ ( s e l f ,h o u r = 0 ,m i n u t e = 0 ,s e c o n d = 0 ) : s e l f . h o u r=h o u r s e l f . m i n u t e=m i n u t e
en.wikibooks.org/wiki/Think_Python/Print_version 178/282
10/24/13
s e l f . s e c o n d=s e c o n d
Itiscommonfortheparametersof _ _ i n i t _ _ tohavethesamenamesastheattributes.Thestatement
s e l f . h o u r=h o u r
Ifyouprovideoneargument,itoverrides h o u r :
> > >t i m e=T i m e( 9 ) > > >t i m e . p r i n t _ t i m e ( ) 0 9 : 0 0 : 0 0
Ifyouprovidetwoarguments,theyoverride h o u r and m i n u t e .
> > >t i m e=T i m e ( 9 ,4 5 ) > > >t i m e . p r i n t _ t i m e ( ) 0 9 : 4 5 : 0 0
Andifyouprovidethreearguments,theyoverrideallthreedefaultvalues.
Exercise2
Writeaninitmethodforthe'P o i n t 'classthattakes'x 'and'y 'asoptionalparametersandassignsthemtothecorrespondingattributes.
The_ _ s t r _ _ method
_ _ s t r _ _ isaspecialmethod,like _ _ i n i t _ _ ,thatissupposedtoreturnastringrepresentationofanobject.
Forexample,hereisa s t r methodforTimeobjects:
#i n s i d ec l a s sT i m e :
en.wikibooks.org/wiki/Think_Python/Print_version 179/282
10/24/13
d e f_ _ s t r _ _ ( s e l f ) : r e t u r n' % . 2 d : % . 2 d : % . 2 d '%( s e l f . h o u r ,s e l f . m i n u t e ,s e l f . s e c o n d )
Exercise3
Writea's t r 'methodforthe'P o i n t 'class.CreateaPointobjectandprintit.
Operatoroverloading
Bydefiningotherspecialmethods,youcanspecifythebehaviorofoperatorsonuserdefinedtypes.Forexample,ifyoudefineamethodnamed _ _ a d d _ _ forthe T i m e class,youcanusethe + operatoronTimeobjects. Hereiswhatthedefinitionmightlooklike:
#i n s i d ec l a s sT i m e : d e f_ _ a d d _ _ ( s e l f ,o t h e r ) : s e c o n d s=s e l f . t i m e _ t o _ i n t ( )+o t h e r . t i m e _ t o _ i n t ( ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s )
Andhereishowyoucoulduseit:
> > >s t a r t=T i m e ( 9 ,4 5 ) > > >d u r a t i o n=T i m e ( 1 ,3 5 ) > > >p r i n ts t a r t+d u r a t i o n 1 1 : 2 0 : 0 0
10/24/13
Exercise4
Writean'a d d 'methodforthePointclass.
Typebaseddispatch
IntheprevioussectionweaddedtwoTimeobjects,butyoualsomightwanttoaddanintegertoaTimeobject.Thefollowingisaversionof _ _ a d d _ _ that checksthetypeof o t h e r andinvokeseither a d d _ t i m e or i n c r e m e n t :
#i n s i d ec l a s sT i m e : d e f_ _ a d d _ _ ( s e l f ,o t h e r ) : i fi s i n s t a n c e ( o t h e r ,T i m e ) : r e t u r ns e l f . a d d _ t i m e ( o t h e r ) e l s e : r e t u r ns e l f . i n c r e m e n t ( o t h e r ) d e fa d d _ t i m e ( s e l f ,o t h e r ) : s e c o n d s=s e l f . t i m e _ t o _ i n t ( )+o t h e r . t i m e _ t o _ i n t ( ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s ) d e fi n c r e m e n t ( s e l f ,s e c o n d s ) : s e c o n d s+ =s e l f . t i m e _ t o _ i n t ( ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s )
Thebuiltinfunction i s i n s t a n c e takesavalueandaclassobject,andreturns T r u e ifthevalueisaninstanceoftheclass. If o t h e r isaTimeobject, _ _ a d d _ _ invokes a d d _ t i m e .Otherwiseitassumesthattheparameterisanumberandinvokes i n c r e m e n t .Thisoperationiscalleda type baseddispatchbecauseitdispatchesthecomputationtodifferentmethodsbasedonthetypeofthearguments. Hereareexamplesthatusethe + operatorwithdifferenttypes:
> > >s t a r t=T i m e ( 9 ,4 5 ) > > >d u r a t i o n=T i m e ( 1 ,3 5 ) > > >p r i n ts t a r t+d u r a t i o n 1 1 : 2 0 : 0 0 > > >p r i n ts t a r t+1 3 3 7 1 0 : 0 7 : 1 7
Unfortunately,thisimplementationofadditionisnotcommutative.Iftheintegeristhefirstoperand,youget
> > >p r i n t1 3 3 7+s t a r t T y p e E r r o r :u n s u p p o r t e do p e r a n dt y p e ( s )f o r+ :' i n t 'a n d' i n s t a n c e '
en.wikibooks.org/wiki/Think_Python/Print_version
181/282
10/24/13
Andhereshowitsused:
> > >p r i n t1 3 3 7+s t a r t 1 0 : 0 7 : 1 7
Exercise5
Writean'a d d 'methodforPointsthatworkswitheitheraPointobjectoratuple: IfthesecondoperandisaPoint,themethodshouldreturnanewPointwhose'x'coordinateisthesumofthe'x'coordinatesoftheoperands,and likewiseforthe'y'coordinates. Ifthesecondoperandisatuple,themethodshouldaddthefirstelementofthetupletothe'x'coordinateandthesecondelementtothe'y'coordinate, andreturnanewPointwiththeresult.
Polymorphism
Typebaseddispatchisusefulwhenitisnecessary,but(fortunately)itisnotalwaysnecessary.Oftenyoucanavoiditbywritingfunctionsthatworkcorrectly forargumentswithdifferenttypes. Manyofthefunctionswewroteforstringswillactuallyworkforanykindofsequence.Forexample,inSection11.1weused h i s t o g r a m tocountthenumberof timeseachletterappearsinaword.
d e fh i s t o g r a m ( s ) : d=d i c t ( ) f o rci ns : i fcn o ti nd : d [ c ]=1 e l s e : d [ c ]=d [ c ] + 1 r e t u r nd
Thisfunctionalsoworksforlists,tuples,andevendictionaries,aslongastheelementsof s arehashable,sotheycanbeusedaskeysin d .
en.wikibooks.org/wiki/Think_Python/Print_version 182/282
10/24/13
> > >t=[ ' s p a m ' ,' e g g ' ,' s p a m ' ,' s p a m ' ,' b a c o n ' ,' s p a m ' ] > > >h i s t o g r a m ( t ) { ' b a c o n ' :1 ,' e g g ' :1 ,' s p a m ' :4 }
Ingeneral,ifalloftheoperationsinsideafunctionworkwithagiventype,thenthefunctionworkswiththattype. Thebestkindofpolymorphismistheunintentionalkind,whereyoudiscoverthatafunctionyoualreadywrotecanbeappliedtoatypeyouneverplannedfor.
Debugging
Itislegaltoaddattributestoobjectsatanypointintheexecutionofaprogram,butifyouareasticklerfortypetheory,itisadubiouspracticetohaveobjects ofthesametypewithdifferentattributesets.Itisusuallyagoodideatoinitializeallofanobjectsattributesintheinitmethod. Ifyouarenotsurewhetheranobjecthasaparticularattribute,youcanusethebuiltinfunction h a s a t t r (seeSection15.7). Anotherwaytoaccesstheattributesofanobjectisthroughthespecialattribute _ _ d i c t _ _ ,whichisadictionarythatmapsattributenames(asstrings)and values:
> > >p=P o i n t ( 3 ,4 ) > > >p r i n tp . _ _ d i c t _ _ { ' y ' :4 ,' x ' :3 }
Forpurposesofdebugging,youmightfinditusefultokeepthisfunctionhandy:
d e fp r i n t _ a t t r i b u t e s ( o b j ) : f o ra t t ri no b j . _ _ d i c t _ _ : p r i n ta t t r ,g e t a t t r ( o b j ,a t t r )
p r i n t _ a t t r i b u t e s traversestheitemsintheobjectsdictionaryandprintseachattributenameanditscorrespondingvalue.
en.wikibooks.org/wiki/Think_Python/Print_version 183/282
10/24/13
Thebuiltinfunction g e t a t t r takesanobjectandanattributename(asastring)andreturnstheattributesvalue.
Glossary
objectorientedlanguage: Alanguagethatprovidesfeatures,suchasuserdefinedclassesandmethodsyntax,thatfacilitateobjectorientedprogramming. objectorientedprogramming: Astyleofprogramminginwhichdataandtheoperationsthatmanipulateitareorganizedintoclassesandmethods. method: Afunctionthatisdefinedinsideaclassdefinitionandisinvokedoninstancesofthatclass. subject: Theobjectamethodisinvokedon. operatoroverloading: Changingthebehaviorofanoperatorlike + soitworkswithauserdefinedtype. typebaseddispatch: Aprogrammingpatternthatchecksthetypeofanoperandandinvokesdifferentfunctionsfordifferenttypes. polymorphic: Pertainingtoafunctionthatcanworkwithmorethanonetype.
Exercises
Exercise6
Thisexerciseisacautionarytaleaboutoneofthemost common,anddifficulttofind,errorsinPython. Writeadefinitionforaclassnamed'K a n g a r o o 'withthefollowing methods: An _ _ i n i t _ _ methodthatinitializesanattributenamed p o u c h _ c o n t e n t s toanemptylist. Amethodnamed p u t _ i n _ p o u c h thattakesanobjectofanytypeandaddsitto p o u c h _ c o n t e n t s . A_ _ s t r _ _ methodthatreturnsastringrepresentationoftheKangarooobjectandthecontentsofthepouch. Testyourcodebycreatingtwo'''K a n g a r o o '''objects,assigningthemtovariablesnamed'''k a n g a '''and'''r o o ''',andthenadding'''r o o '''tothecontentsof'''k a n g a '''s pouch.' 'Download'''t h i n k p y t h o n . c o m / c o d e / B a d K a n g a r o o . p y '''.Itcontains
en.wikibooks.org/wiki/Think_Python/Print_version 184/282
10/24/13
Exercise7
VisualisaPythonmodulethatprovides3Dgraphics.ItisnotalwaysincludedinaPythoninstallation,soyoumighthavetoinstallitfromyoursoftware repositoryor,ifitsnotthere,from'v p y t h o n . o r g '. Thefollowingexamplecreatesa3Dspacethatis256unitswide,longandhigh,andsetsthecentertobethepoint'(128,128,128)'.Thenitdrawsablue sphere.
' ' f r o mv i s u a li m p o r t* s c e n e . r a n g e=( 2 5 6 ,2 5 6 ,2 5 6 ) s c e n e . c e n t e r=( 1 2 8 ,1 2 8 ,1 2 8 ) c o l o r=( 0 . 1 ,0 . 1 ,0 . 9 ) #m o s t l yb l u e s p h e r e ( p o s = s c e n e . c e n t e r ,r a d i u s = 1 2 8 ,c o l o r = c o l o r ) ' '
c o l o r ''isanRGBtuplethatis,theelementsareRedGreenBluelevelsbetween0.0and1.0(see'w i k i p e d i a . o r g / w i k i / R G B _ c o l o r _ m o d e l ').
10/24/13
Furtherreading
Wikipedia:VPython Wikipedia:RGBcolormodel
Inheritance
Inthischapterwewilldevelopclassestorepresentplayingcards,decksofcards,andpokerhands.Ifyoudontplaypoker,youcanreadaboutitat w i k i p e d i a . o r g / w i k i / P o k e r (http://en.wikipedia.org/wiki/Poker),butyoudon'thavetoI'lltellyouwhatyouneedtoknowfortheexercises. IfyouarenotfamiliarwithAngloAmericanplayingcards,youcanreadaboutthemat w i k i p e d i a . o r g / w i k i / P l a y i n g _ c a r d s (http://en.wikipedia.org/wiki/Playing_cards).
Cardobjects
Therearefiftytwocardsinadeck,eachofwhichbelongstooneoffoursuitsandoneofthirteenranks.ThesuitsareSpades,Hearts,Diamonds,andClubs (indescendingorderinbridge).TheranksareAce,2,3,4,5,6,7,8,9,10,Jack,Queen,andKing.Dependingonthegamethatyouareplaying,anAcemay behigherthanKingorlowerthan2. Ifwewanttodefineanewobjecttorepresentaplayingcard,itisobviouswhattheattributesshouldbe: r a n k and s u i t .Itisnotasobviouswhattypethe attributesshouldbe.Onepossibilityistousestringscontainingwordslike ' S p a d e ' forsuitsand ' Q u e e n ' forranks.Oneproblemwiththisimplementationisthatit wouldnotbeeasytocomparecardstoseewhichhadahigherrankorsuit. Analternativeistouseintegersto encodetheranksandsuits.Inthiscontext,encodemeansthatwearegoingtodefineamappingbetweennumbersand suits,orbetweennumbersandranks.Thiskindofencodingisnotmeanttobeasecret(thatwouldbeencryption). Forexample,thistableshowsthesuitsandthecorrespondingintegercodes: Spades Hearts 3 2
Diamonds 1 Clubs 0
Thiscodemakesiteasytocomparecardsbecausehighersuitsmaptohighernumbers,wecancomparesuitsbycomparingtheircodes. Themappingforranksisfairlyobviouseachofthenumericalranksmapstothecorrespondinginteger,andforfacecards:
en.wikibooks.org/wiki/Think_Python/Print_version 186/282
10/24/13
Jack
11
Queen 12 King 13
Classattributes
InordertoprintCardobjectsinawaythatpeoplecaneasilyread,weneedamappingfromtheintegercodestothecorrespondingranksandsuits.Anatural waytodothatiswithlistsofstrings.Weassigntheseliststo classattributes:
#i n s i d ec l a s sC a r d : s u i t _ n a m e s=[ ' C l u b s ' ,' D i a m o n d s ' ,' H e a r t s ' ,' S p a d e s ' ] r a n k _ n a m e s=[ N o n e ,' A c e ' ,' 2 ' ,' 3 ' ,' 4 ' ,' 5 ' ,' 6 ' ,' 7 ' , ' 8 ' ,' 9 ' ,' 1 0 ' ,' J a c k ' ,' Q u e e n ' ,' K i n g ' ] d e f_ _ s t r _ _ ( s e l f ) : r e t u r n' % so f% s '%( C a r d . r a n k _ n a m e s [ s e l f . r a n k ] , C a r d . s u i t _ n a m e s [ s e l f . s u i t ] )
10/24/13
Bothkindsofattributeareaccessedusingdotnotation.Forexample,in _ _ s t r _ _ , s e l f isaCardobject,and s e l f . r a n k isitsrank.Similarly, C a r d isaclassobject, and C a r d . r a n k _ n a m e s isalistofstringsassociatedwiththeclass. Everycardhasitsown s u i t and r a n k ,butthereisonlyonecopyof s u i t _ n a m e s and r a n k _ n a m e s . Puttingitalltogether,theexpression C a r d . r a n k _ n a m e s [ s e l f . r a n k ] meansusetheattribute r a n k fromtheobject s e l f asanindexintothelist r a n k _ n a m e s fromtheclass C a r d ,andselecttheappropriatestring. Thefirstelementof r a n k _ n a m e s is N o n e becausethereisnocardwithrankzero.Byincluding N o n e asaplacekeeper,wegetamappingwiththenicepropertythat theindex2mapstothestring ' 2 ' ,andsoon.Toavoidthistweak,wecouldhaveusedadictionaryinsteadofalist. Withthemethodswehavesofar,wecancreateandprintcards:
> > >c a r d 1=C a r d ( 2 ,1 1 ) > > >p r i n tc a r d 1 J a c ko fH e a r t s
Comparingcards
Forbuiltintypes,thereareconditionaloperators(< , > , = = ,etc.)thatcomparevaluesanddeterminewhenoneisgreaterthan,lessthan,orequaltoanother. Foruserdefinedtypes,wecanoverridethebehaviorofthebuiltinoperatorsbyprovidingamethodnamed _ _ c m p _ _ .
_ _ c m p _ _ takestwoparameters, s e l f and o t h e r ,andreturnsapositivenumberifthefirstobjectisgreater,anegativenumberifthesecondobjectisgreater,and0
10/24/13
Youcanwritethismoreconciselyusingtuplecomparison:
#i n s i d ec l a s sC a r d : d e f_ _ c m p _ _ ( s e l f ,o t h e r ) : t 1=s e l f . s u i t ,s e l f . r a n k t 2=o t h e r . s u i t ,o t h e r . r a n k r e t u r nc m p ( t 1 ,t 2 )
Exercise1
Writea _ _ c m p _ _ methodforTimeobjects.Hint:youcanusetuplecomparison,butyoualsomightconsiderusingintegersubtraction.
Decks
NowthatwehaveCards,thenextstepistodefineDecks.Sinceadeckismadeupofcards,itisnaturalforeachDecktocontainalistofcardsasan attribute. Thefollowingisaclassdefinitionfor D e c k .Theinitmethodcreatestheattribute c a r d s andgeneratesthestandardsetoffiftytwocards:
c l a s sD e c k : d e f_ _ i n i t _ _ ( s e l f ) : s e l f . c a r d s=[ ] f o rs u i ti nr a n g e ( 4 ) : f o rr a n ki nr a n g e ( 1 ,1 4 ) : c a r d=C a r d ( s u i t ,r a n k ) s e l f . c a r d s . a p p e n d ( c a r d )
Theeasiestwaytopopulatethedeckiswithanestedloop.Theouterloopenumeratesthesuitsfrom0to3.Theinnerloopenumeratestheranksfrom1to 13.EachiterationcreatesanewCardwiththecurrentsuitandrank,andappendsitto s e l f . c a r d s .
en.wikibooks.org/wiki/Think_Python/Print_version 189/282
10/24/13
Printingthedeck
Hereisa _ _ s t r _ _ methodfor D e c k :
# i n s i d ec l a s sD e c k : d e f_ _ s t r _ _ ( s e l f ) : r e s=[ s t r ( c a r d )f o rc a r di ns e l f . c a r d s ] r e t u r n' \ n ' . j o i n ( r e s )
Eventhoughtheresultappearson52lines,itisonelongstringthatcontainsnewlines.
Add,remove,shuffleandsort
Todealcards,wewouldlikeamethodthatremovesacardfromthedeckandreturnsit.Thelistmethod p o p providesaconvenientwaytodothat:
# i n s i d ec l a s sD e c k : d e fp o p _ c a r d ( s e l f ) : r e t u r ns e l f . c a r d s . p o p ( )
10/24/13
d e fa d d _ c a r d ( s e l f ,c a r d ) : s e l f . c a r d s . a p p e n d ( c a r d )
Dontforgettoimport r a n d o m .
Exercise2
WriteaDeckmethodnamed's o r t 'thatusesthelistmethod's o r t 'tosortthecardsina'D e c k '.'s o r t 'usesthe _ _ c m p _ _ methodwedefinedtodeterminesortorder.
Inheritance
Thelanguagefeaturemostoftenassociatedwithobjectorientedprogrammingis inheritance.Inheritanceistheabilitytodefineanewclassthatisamodified versionofanexistingclass. Itiscalledinheritancebecausethenewclassinheritsthemethodsoftheexistingclass.Extendingthismetaphor,theexistingclassiscalledthe parentand thenewclassiscalledthe child. Asanexample,letssaywewantaclasstorepresentahand,thatis,thesetofcardsheldbyoneplayer.Ahandissimilartoadeck:botharemadeupofa setofcards,andbothrequireoperationslikeaddingandremovingcards. Ahandisalsodifferentfromadeckthereareoperationswewantforhandsthatdontmakesenseforadeck.Forexample,inpokerwemightcomparetwo handstoseewhichonewins.Inbridge,wemightcomputeascoreforahandinordertomakeabid. Thisrelationshipbetweenclassessimilar,butdifferentlendsitselftoinheritance. Thedefinitionofachildclassislikeotherclassdefinitions,butthenameoftheparentclassappearsinparentheses:
c l a s sH a n d ( D e c k ) : " " " r e p r e s e n t sah a n do fp l a y i n gc a r d s " " "
en.wikibooks.org/wiki/Think_Python/Print_version
191/282
10/24/13
SowhenyoucreateaHand,Pythoninvokesthisinitmethod:
> > >h a n d=H a n d ( ' n e wh a n d ' ) > > >p r i n th a n d . c a r d s [ ] > > >p r i n th a n d . l a b e l n e wh a n d
Anaturalnextstepistoencapsulatethiscodeinamethodcalled m o v e _ c a r d s :
# i n s i d ec l a s sD e c k : d e fm o v e _ c a r d s ( s e l f ,h a n d ,n u m ) : f o rii nr a n g e ( n u m ) : h a n d . a d d _ c a r d ( s e l f . p o p _ c a r d ( ) )
m o v e _ c a r d s takestwoarguments,aHandobjectandthenumberofcardstodeal.Itmodifiesboth s e l f and h a n d ,andreturns N o n e .
en.wikibooks.org/wiki/Think_Python/Print_version
192/282
10/24/13
Classdiagrams
Sofarwehaveseenstackdiagrams,whichshowthestateofaprogram,andobjectdiagrams,whichshowtheattributesofanobjectandtheirvalues.These diagramsrepresentasnapshotintheexecutionofaprogram,sotheychangeastheprogramruns. Theyarealsohighlydetailedforsomepurposes,toodetailed.Aclassdiagramsisamoreabstractrepresentationofthestructureofaprogram.Insteadof showingindividualobjects,itshowsclassesandtherelationshipsbetweenthem. Thereareseveralkindsofrelationshipbetweenclasses: Objectsinoneclassmightcontainreferencestoobjectsinanotherclass.Forexample,eachRectanglecontainsareferencetoaPoint,andeachDeck containsreferencestomanyCards.Thiskindofrelationshipiscalled HASA,asin,aRectanglehasaPoint. Oneclassmightinheritfromanother.Thisrelationshipiscalled ISA,asin,aHandisakindofaDeck. Oneclassmightdependonanotherinthesensethatchangesinoneclasswouldrequirechangesintheother. A classdiagramisagraphicalrepresentationoftheserelationships2.Forexample,thisdiagramshowstherelationshipsbetween C a r d , D e c k and H a n d . <IMGSRC="book027.png"> ThearrowwithahollowtriangleheadrepresentsanISArelationshipinthiscaseitindicatesthatHandinheritsfromDeck. ThestandardarrowheadrepresentsaHASArelationshipinthiscaseaDeckhasreferencestoCardobjects. Thestar(* )nearthearrowheadisa multiplicityitindicateshowmanyCardsaDeckhas.Amultiplicitycanbeasimplenumber,like 5 2 ,arange,like 5 . . 7 or astar,whichindicatesthataDeckcanhaveanynumberofCards. AmoredetaileddiagrammightshowthataDeckactuallycontainsa list ofCards,butbuiltintypeslikelistanddictareusuallynotincludedinclassdiagrams.
Exercise4
Read'T u r t l e W o r l d . p y ','W o r l d . p y 'and'G u i . p y 'anddrawaclassdiagramthatshowstherelationshipsamongtheclassesdefinedthere.
en.wikibooks.org/wiki/Think_Python/Print_version 193/282
10/24/13
Debugging
Inheritancecanmakedebuggingachallengebecausewhenyouinvokeamethodonanobject,youmightnotknowwhichmethodwillbeinvoked. SupposeyouarewritingafunctionthatworkswithHandobjects.YouwouldlikeittoworkwithallkindsofHands,likePokerHands,BridgeHands,etc.Ifyou invokeamethodlike s h u f f l e ,youmightgettheonedefinedin D e c k ,butifanyofthesubclassesoverridethismethod,youllgetthatversioninstead. Anytimeyouareunsureabouttheflowofexecutionthroughyourprogram,thesimplestsolutionistoaddprintstatementsatthebeginningoftherelevant methods.If D e c k . s h u f f l e printsamessagethatsayssomethinglike R u n n i n gD e c k . s h u f f l e ,thenastheprogramrunsittracestheflowofexecution. Asanalternative,youcouldusethisfunction,whichtakesanobjectandamethodname(asastring)andreturnstheclassthatprovidesthedefinitionofthe method:
d e ff i n d _ d e f i n i n g _ c l a s s ( o b j ,m e t h _ n a m e ) : f o rt yi nt y p e ( o b j ) . m r o ( ) : i fm e t h _ n a m ei nt y . _ _ d i c t _ _ : r e t u r nt y
Heresanexample:
> > >h a n d=H a n d ( ) > > >p r i n tf i n d _ d e f i n i n g _ c l a s s ( h a n d ,' s h u f f l e ' ) < c l a s s' C a r d . D e c k ' >
Sothe s h u f f l e methodforthisHandistheonein D e c k .
f i n d _ d e f i n i n g _ c l a s s usesthe m r o methodtogetthelistofclassobjects(types)thatwillbesearchedformethods.MROstandsformethodresolutionorder.
Glossary
encode: Torepresentonesetofvaluesusinganothersetofvaluesbyconstructingamappingbetweenthem. classattribute: Anattributeassociatedwithaclassobject.Classattributesaredefinedinsideaclassdefinitionbutoutsideanymethod. instanceattribute: Anattributeassociatedwithaninstanceofaclass.
en.wikibooks.org/wiki/Think_Python/Print_version 194/282
10/24/13
veneer: Amethodorfunctionthatprovidesadifferentinterfacetoanotherfunctionwithoutdoingmuchcomputation. inheritance: Theabilitytodefineanewclassthatisamodifiedversionofapreviouslydefinedclass. parentclass: Theclassfromwhichachildclassinherits. childclass: Anewclasscreatedbyinheritingfromanexistingclassalsocalledasubclass. ISArelationship: Therelationshipbetweenachildclassanditsparentclass. HASArelationship: Therelationshipbetweentwoclasseswhereinstancesofoneclasscontainreferencestoinstancesoftheother. classdiagram: Adiagramthatshowstheclassesinaprogramandtherelationshipsbetweenthem. multiplicity: Anotationinaclassdiagramthatshows,foraHASArelationship,howmanyreferencestherearetoinstancesofanotherclass.
Exercises
Exercise5
Thefollowingarethepossiblehandsinpoker,inincreasingorderofvalue(anddecreasingorderofprobability): pair: twocardswiththesamerank ''twopair:'' twopairsofcardswiththesamerank ''threeofakind:'' threecardswiththesamerank ''straight:'' fivecardswithranksinsequence(acescanbehighorlow,so'A c e 2 3 4 5 'isastraightandsois'1 0 J a c k Q u e e n K i n g A c e ',but'Q u e e n K i n g A c e 2 3 'isnot.) ''flush:'' fivecardswiththesamesuit ''fullhouse:'' threecardswithonerank,twocardswithanother ''fourofakind:''
en.wikibooks.org/wiki/Think_Python/Print_version 195/282
10/24/13
:Acompleteversionofthe'C a r d ','D e c k 'and'H a n d 'classesinthischapter. ''P o k e r H a n d . p y '' :Anincompleteimplementationofaclass thatrepresentsapokerhand,andsomecodethattestsit. 'Ifyourun'''P o k e r H a n d . p y ''',itdealssix7cardpokerhands andcheckstoseeifanyofthemcontainsaflush.Readthiscodecarefullybeforeyougoon.' 'Addmethodsto'''P o k e r H a n d . p y ''' named'' h a s _ p a i r ' ', '' h a s _ t w o p a i r ' ',etc.thatreturnTrueorFalseaccordingtowhetherornotthehandmeetstherelevantcriteria.Yourcodeshouldworkcorrectlyforhandsthat containanynumberofcards(although5and7arethemostcommonsizes).' 'Writeamethodnamed'''c l a s s i f y ''' thatfiguresout thehighestvalueclassificationforahandandsetsthe'''l a b e l '''attributeaccordingly.Forexample,a7cardhandmightcontainaflushandapairitshouldbe labeledflush.' 'Whenyouareconvincedthatyourclassificationmethodsare working,thenextstepistoestimatetheprobabilitiesofthevarioushands.Writeafunctionin'''P o k e r H a n d . p y '''thatshufflesadeckofcards,dividesitintohands, classifiesthehands,andcountsthenumberoftimesvariousclassificationsappear.' 'Printatableoftheclassificationsandtheirprobabilities. Runyourprogramwithlargerandlargernumbersofhandsuntiltheoutputvaluesconvergetoareasonabledegreeofaccuracy.Compareyourresultstothe valuesat'''w i k i p e d i a . o r g / w i k i / H a n d _ r a n k i n g s '''.'
Exercise6
196/282
10/24/13
ThisexerciseusesTurtleWorldfromChapter'4'. YouwillwritecodethatmakesTurtlesplaytag.Ifyouarenotfamiliarwiththerulesoftag,see 'w i k i p e d i a . o r g / w i k i / T a g _ ( g a m e ) '. Download't h i n k p y t h o n . c o m / c o d e / W o b b l e r . p y 'andrunit.You shouldseeaTurtleWorldwiththreeTurtles.Ifyoupressthe'Run'button,theTurtleswanderatrandom. Readthecodeandmakesureyouunderstandhowitworks. The'W o b b l e r 'classinheritsfrom'T u r t l e ',whichmeansthatthe'T u r t l e 'methods'l t ','r t ','f d 'and'b k 'workonWobblers. The's t e p 'methodgetsinvokedby TurtleWorld.Itinvokes's t e e r ',whichturnstheTurtleinthedesireddirection,'w o b b l e ',whichmakesarandomturninproportiontotheTurtlesclumsiness,and 'm o v e ',whichmovesforwardafewpixels,dependingontheTurtlesspeed. Createafilenamed'T a g g e r . p y '.Importeverythingfrom 'W o b b l e r ',thendefineaclassnamed'T a g g e r 'thatinheritsfrom'W o b b l e r '.Call m a k e _ w o r l d passingthe'T a g g e r 'classobjectasanargument. Adda's t e e r 'methodto'T a g g e r 'tooverridetheonein 'W o b b l e r '.Asastartingplace,writeaversionthatalwayspointstheTurtletowardtheorigin.Hint:usethemathfunction'a t a n 2 'andtheTurtleattributes'x ','y 'and 'h e a d i n g '. Modify's t e e r 'sothattheTurtlesstayinbounds. Fordebugging,youmightwanttousethe'Step'button,whichinvokes's t e p 'onceoneachTurtle. Modify's t e e r 'sothateachTurtlepointstowarditsnearest neighbor.Hint:Turtleshaveanattribute,'w o r l d ',thatisareferencetotheTurtleWorldtheylivein,andtheTurtleWorldhasanattribute,'a n i m a l s ',thatisalistof allTurtlesintheworld. Modify's t e e r 'sotheTurtlesplaytag.Youcanaddmethods to'T a g g e r 'andyoucanoverride's t e e r 'and _ _ i n i t _ _ ,butyoumaynotmodifyoroverride's t e p ','w o b b l e 'or'm o v e '.Also,'s t e e r 'isallowedtochangetheheadingofthe Turtlebutnottheposition. Adjusttherulesandyour's t e e r 'methodforgoodqualityplay forexample,itshouldbepossiblefortheslowTurtletotagthefaster Turtleseventually. Youcangetmysolutionfrom't h i n k p y t h o n . c o m / c o d e / T a g g e r . p y '.
1 See w i k i p e d i a . o r g / w i k i / B o t t o m _ d e a l i n g .
en.wikibooks.org/wiki/Think_Python/Print_version 197/282
10/24/13
2 ThediagramsIamusingherearesimilartoUML(see w i k i p e d i a . o r g / w i k i / U n i f i e d _ M o d e l i n g _ L a n g u a g e ),withafewsimplifications.
Debugging
Differentkindsoferrorscanoccurinaprogram,anditisusefultodistinguishamongtheminordertotrackthemdownmorequickly: SyntaxerrorsareproducedbyPythonwhenitistranslatingthesourcecodeintobytecode.Theyusuallyindicatethatthereissomethingwrongwiththe syntaxoftheprogram.Example:Omittingthecolonattheendofa d e f statementyieldsthesomewhatredundantmessage S y n t a x E r r o r :i n v a l i ds y n t a x . Runtimeerrorsareproducedbytheinterpreterifsomethinggoeswrongwhiletheprogramisrunning.Mostruntimeerrormessagesincludeinformation aboutwheretheerroroccurredandwhatfunctionswereexecuting.Example:Aninfiniterecursioneventuallycausestheruntimeerrormaximum recursiondepthexceeded. Semanticerrorsareproblemswithaprogramthatrunswithoutproducingerrormessagesbutdoesntdotherightthing.Example:Anexpressionmay notbeevaluatedintheorderyouexpect,yieldinganincorrectresult. Thefirststepindebuggingistofigureoutwhichkindoferroryouaredealingwith.Althoughthefollowingsectionsareorganizedbyerrortype,some techniquesareapplicableinmorethanonesituation.
Syntaxerrors
Syntaxerrorsareusuallyeasytofixonceyoufigureoutwhattheyare.Unfortunately,theerrormessagesareoftennothelpful.Themostcommonmessages are S y n t a x E r r o r :i n v a l i ds y n t a x and S y n t a x E r r o r :i n v a l i dt o k e n ,neitherofwhichisveryinformative. Ontheotherhand,themessagedoestellyouwhereintheprogramtheproblemoccurred.Actually,ittellsyouwherePythonnoticedaproblem,whichisnot necessarilywheretheerroris.Sometimestheerrorispriortothelocationoftheerrormessage,oftenontheprecedingline. Ifyouarebuildingtheprogramincrementally,youshouldhaveagoodideaaboutwheretheerroris.Itwillbeinthelastlineyouadded. Ifyouarecopyingcodefromabook,startbycomparingyourcodetothebookscodeverycarefully.Checkeverycharacter.Atthesametime,rememberthat thebookmightbewrong,soifyouseesomethingthatlookslikeasyntaxerror,itmightbe. Herearesomewaystoavoidthemostcommonsyntaxerrors: MakesureyouarenotusingaPythonkeywordforavariablename. Checkthatyouhaveacolonattheendoftheheaderofevery compoundstatement,including f o r , w h i l e , i f ,and d e f statements.
Makesurethatanystringsinthecodehavematching
en.wikibooks.org/wiki/Think_Python/Print_version 198/282
10/24/13
Anunclosedopeningoperator( , { ,or
[ makesPythoncontinuewiththenextlineaspartofthecurrentstatement.Generally,anerroroccursalmostimmediatelyinthenextline.
Ikeepmakingchangesanditmakesnodifference.
Iftheinterpretersaysthereisanerrorandyoudontseeit,thatmightbebecauseyouandtheinterpreterarenotlookingatthesamecode.Checkyour programmingenvironmenttomakesurethattheprogramyouareeditingistheonePythonistryingtorun. Ifyouarenotsure,tryputtinganobviousanddeliberatesyntaxerroratthebeginningoftheprogram.Nowrunitagain.Iftheinterpreterdoesntfindthenew error,youarenotrunningthenewcode. Thereareafewlikelyculprits: Youeditedthefileandforgottosavethechangesbefore runningitagain.Someprogrammingenvironmentsdothisforyou,butsomedont. Youchangedthenameofthefile,butyouarestillrunning theoldname. Somethinginyourdevelopmentenvironmentisconfigured incorrectly.
en.wikibooks.org/wiki/Think_Python/Print_version 199/282
10/24/13
Ifyouarewritingamoduleandusing i m p o r t , makesureyoudontgiveyourmodulethesamenameasoneofthestandardPythonmodules.
Runtimeerrors
Onceyourprogramissyntacticallycorrect,Pythoncancompileitandatleaststartrunningit.Whatcouldpossiblygowrong?
Myprogramdoesabsolutelynothing.
Thisproblemismostcommonwhenyourfileconsistsoffunctionsandclassesbutdoesnotactuallyinvokeanythingtostartexecution.Thismaybeintentional ifyouonlyplantoimportthismoduletosupplyclassesandfunctions. Ifitisnotintentional,makesurethatyouareinvokingafunctiontostartexecution,orexecuteonefromtheinteractiveprompt.AlsoseetheFlowof Executionsectionbelow.
Myprogramhangs.
Ifaprogramstopsandseemstobedoingnothing,itishanging.Oftenthatmeansthatitiscaughtinaninfinitelooporinfiniterecursion. Ifthereisaparticularloopthatyoususpectisthe problem,adda p r i n t statementimmediatelybeforetheloopthatsaysenteringtheloopandanotherimmediatelyafterthatsaysexitingtheloop.Runthe program.Ifyougetthefirstmessageandnotthesecond,youvegotaninfiniteloop.GototheInfiniteLoopsectionbelow. Mostofthetime,aninfiniterecursionwillcausetheprogram torunforawhileandthenproduceaRuntimeError:Maximumrecursiondepthexceedederror.Ifthathappens,gototheInfiniteRecursionsectionbelow.If youarenotgettingthiserrorbutyoususpectthereisaproblemwitharecursivemethodorfunction,youcanstillusethetechniquesintheInfiniteRecursion section. Ifneitherofthosestepsworks,starttestingother
en.wikibooks.org/wiki/Think_Python/Print_version
200/282
10/24/13
Nowwhenyouruntheprogram,youwillseethreelinesofoutputforeachtimethroughtheloop.Thelasttimethroughtheloop,theconditionshouldbe f a l s e . Iftheloopkeepsgoing,youwillbeabletoseethevaluesof x and y ,andyoumightfigureoutwhytheyarenotbeingupdatedcorrectly. InfiniteRecursion Mostofthetime,aninfiniterecursionwillcausetheprogramtorunforawhileandthenproducea M a x i m u mr e c u r s i o nd e p t he x c e e d e d error. Ifyoususpectthatafunctionormethodiscausinganinfiniterecursion,startbycheckingtomakesurethatthereisabasecase.Inotherwords,thereshould besomeconditionthatwillcausethefunctionormethodtoreturnwithoutmakingarecursiveinvocation.Ifnot,thenyouneedtorethinkthealgorithmand identifyabasecase. Ifthereisabasecasebuttheprogramdoesntseemtobereachingit,adda p r i n t statementatthebeginningofthefunctionormethodthatprintsthe parameters.Nowwhenyouruntheprogram,youwillseeafewlinesofoutputeverytimethefunctionormethodisinvoked,andyouwillseetheparameters. Iftheparametersarenotmovingtowardthebasecase,youwillgetsomeideasaboutwhynot. FlowofExecution Ifyouarenotsurehowtheflowofexecutionismovingthroughyourprogram,add p r i n t statementstothebeginningofeachfunctionwithamessagelike enteringfunction f o o ,where f o o isthenameofthefunction. Nowwhenyouruntheprogram,itwillprintatraceofeachfunctionasitisinvoked.
en.wikibooks.org/wiki/Think_Python/Print_version 201/282
10/24/13
WhenIruntheprogramIgetanexception.
Ifsomethinggoeswrongduringruntime,Pythonprintsamessagethatincludesthenameoftheexception,thelineoftheprogramwheretheproblem occurred,andatraceback. Thetracebackidentifiesthefunctionthatiscurrentlyrunning,andthenthefunctionthatinvokedit,andthenthefunctionthatinvoked that ,andsoon.Inother words,ittracesthesequenceoffunctioninvocationsthatgotyoutowhereyouare.Italsoincludesthelinenumberinyourfilewhereeachofthesecalls occurs. Thefirststepistoexaminetheplaceintheprogramwheretheerroroccurredandseeifyoucanfigureoutwhathappened.Thesearesomeofthemost commonruntimeerrors: NameError: Youaretryingtouseavariablethatdoesntexistinthecurrentenvironment.Rememberthatlocalvariablesarelocal.Youcannotrefertothemfrom outsidethefunctionwheretheyaredefined. TypeError: Thereareseveralpossiblecauses: Youaretryingtouseavalueimproperly.Example:indexing astring,list,ortuplewithsomethingotherthananinteger. Thereisamismatchbetweentheitemsinaformatstringand theitemspassedforconversion.Thiscanhappenifeitherthenumberofitemsdoesnotmatchoraninvalidconversioniscalledfor. Youarepassingthewrongnumberofargumentstoafunctionormethod. Formethods,lookatthemethoddefinitionandcheckthatthefirstparameteris s e l f .Thenlookatthemethodinvocationmakesureyouareinvoking themethodonanobjectwiththerighttypeandprovidingtheotherargumentscorrectly. KeyError: Youaretryingtoaccessanelementofadictionaryusingakeythatthedictionarydoesnotcontain. AttributeError: Youaretryingtoaccessanattributeormethodthatdoesnotexist.Checkthespelling!Youcanuse d i r tolisttheattributesthatdoexist.Ifan AttributeErrorindicatesthatanobjecthas N o n e T y p e ,thatmeansthatitis N o n e .Onecommoncauseisforgettingtoreturnavaluefromafunctionifyou gettotheendofafunctionwithouthittinga r e t u r n statement,itreturns N o n e .Anothercommoncauseisusingtheresultfromalistmethod,like s o r t ,that returns N o n e . IndexError: Theindexyouareusingtoaccessalist,string,ortupleisgreaterthanitslengthminusone.Immediatelybeforethesiteoftheerror,adda p r i n t statementtodisplaythevalueoftheindexandthelengthofthearray.Isthearraytherightsize?Istheindextherightvalue?
en.wikibooks.org/wiki/Think_Python/Print_version 202/282
10/24/13
ThePythondebugger(p d b )isusefulfortrackingdownExceptionsbecauseitallowsyoutoexaminethestateoftheprogramimmediatelybeforetheerror.You canreadabout p d b at d o c s . p y t h o n . o r g / l i b / m o d u l e p d b . h t m l . Iaddedsomany p r i n t statementsIgetinundatedwithoutput. Oneoftheproblemswithusing p r i n t statementsfordebuggingisthatyoucanendupburiedinoutput.Therearetwowaystoproceed:simplifytheoutputor simplifytheprogram. Tosimplifytheoutput,youcanremoveorcommentout p r i n t statementsthatarenthelping,orcombinethem,orformattheoutputsoitiseasierto understand. Tosimplifytheprogram,thereareseveralthingsyoucando.First,scaledowntheproblemtheprogramisworkingon.Forexample,ifyouaresearchingalist, searcha smalllist.Iftheprogramtakesinputfromtheuser,giveitthesimplestinputthatcausestheproblem. Second,cleanuptheprogram.Removedeadcodeandreorganizetheprogramtomakeitaseasytoreadaspossible.Forexample,ifyoususpectthatthe problemisinadeeplynestedpartoftheprogram,tryrewritingthatpartwithsimplerstructure.Ifyoususpectalargefunction,trysplittingitintosmaller functionsandtestingthemseparately.
Semanticerrors
Insomeways,semanticerrorsarethehardesttodebug,becausetheinterpreterprovidesnoinformationaboutwhatiswrong.Onlyyouknowwhatthe programissupposedtodo. Thefirststepistomakeaconnectionbetweentheprogramtextandthebehavioryouareseeing.Youneedahypothesisaboutwhattheprogramisactually doing.Oneofthethingsthatmakesthathardisthatcomputersrunsofast. Youwilloftenwishthatyoucouldslowtheprogramdowntohumanspeed,andwithsomedebuggersyoucan.Butthetimeittakestoinsertafewwellplaced p r i n t statementsisoftenshortcomparedtosettingupthedebugger,insertingandremovingbreakpoints,andsteppingtheprogramtowheretheerroris occurring.
Myprogramdoesntwork.
Youshouldaskyourselfthesequestions: Istheresomethingtheprogramwassupposedtodobut
en.wikibooks.org/wiki/Think_Python/Print_version 203/282
10/24/13
A.3.2IvegotabighairyexpressionanditdoesntdowhatIexpect.
Thiscanberewrittenas:
n e i g h b o r=s e l f . f i n d N e i g h b o r ( i ) p i c k e d C a r d=s e l f . h a n d s [ n e i g h b o r ] . p o p C a r d ( ) s e l f . h a n d s [ i ] . a d d C a r d ( p i c k e d C a r d )
Theexplicitversioniseasiertoreadbecausethevariablenamesprovideadditionaldocumentation,anditiseasiertodebugbecauseyoucancheckthetypes oftheintermediatevariablesanddisplaytheirvalues.
en.wikibooks.org/wiki/Think_Python/Print_version
204/282
10/24/13
Wheneveryouarenotsureoftheorderofevaluation,useparentheses.Notonlywilltheprogrambecorrect(inthesenseofdoingwhatyouintended),itwill alsobemorereadableforotherpeoplewhohaventmemorizedtherulesofprecedence.
A.3.3IvegotafunctionormethodthatdoesntreturnwhatIexpect.
youcouldwrite:
c o u n t=s e l f . h a n d s [ i ] . r e m o v e M a t c h e s ( ) r e t u r nc o u n t
Nowyouhavetheopportunitytodisplaythevalueof c o u n t beforereturning.
I'mreally,reallystuckandIneedhelp.
First,trygettingawayfromthecomputerforafewminutes.Computersemitwavesthataffectthebrain,causingthesesymptoms: Frustrationandrage.
en.wikibooks.org/wiki/Think_Python/Print_version 205/282
10/24/13
No,Ireallyneedhelp.
Ithappens.Eventhebestprogrammersoccasionallygetstuck.Sometimesyouworkonaprogramsolongthatyoucantseetheerror.Afreshpairofeyesis justthething. Beforeyoubringsomeoneelsein,makesureyouareprepared.Yourprogramshouldbeassimpleaspossible,andyoushouldbeworkingonthesmallest inputthatcausestheerror.Youshouldhave p r i n t statementsintheappropriateplaces(andtheoutputtheyproduceshouldbecomprehensible).Youshould understandtheproblemwellenoughtodescribeitconcisely. Whenyoubringsomeoneintohelp,besuretogivethemtheinformationtheyneed: Ifthereisanerrormessage,whatisit andwhatpartoftheprogramdoesitindicate? Whatwasthelastthingyoudidbeforethiserroroccurred? Whatwerethelastlinesofcodethatyouwrote,orwhatisthenewtestcasethatfails? Whathaveyoutriedsofar,andwhathaveyoulearned? Whenyoufindthebug,takeasecondtothinkaboutwhatyoucouldhavedonetofinditfaster.Nexttimeyouseesomethingsimilar,youwillbeabletofind thebugmorequickly. Remember,thegoalisnotjusttomaketheprogramwork.Thegoalistolearnhowtomaketheprogramwork.
Answers
Chapter1
SeebelowforChapter1exercises.
en.wikibooks.org/wiki/Think_Python/Print_version 206/282
10/24/13
Exercise1.4
Ifyouruna10kilometerracein43minutes30seconds,whatisyouraveragetimepermile?Whatisyouraveragespeedinmilesperhour?(Hint:thereare 1.61kilometersinamile).
> > >1 0 / 1 . 6 1#C o n v e r tk i l o m e t e r st om i l e s 6 . 2 1 1 1 8 0 1 2 4 2 2 3 6 0 1 8 > > >( 4 3 * 6 0 ) + 3 0#C o n v e r tt i m et os e c o n d s 2 6 1 0 > > >2 6 1 0 / 6 . 2 1 1 1 8 0 1 2 4 2 2 3 6 0 1 8#w h a ti sy o u ra v e r a g et i m e( s e c o n d s )p e rm i l e 4 2 0 . 2 1 0 0 0 0 0 0 0 0 0 0 0 4 > > >4 2 0 . 2 1 0 0 0 0 0 0 0 0 0 0 0 4 / 6 0#w h a ti sy o u ra v e r a g et i m e( m i n u t e s )p e rm i l e 7 . 0 0 3 5 0 0 0 0 0 0 0 0 0 0 0 7 > > >6 0 / 7 . 0 0 3 5 0 0 0 0 0 0 0 0 0 0 0 7#M i l e sp e rh o u r 8 . 5 6 7 1 4 4 9 9 8 9 2 9 1 0 5 5
Comment:Thisisnotvalid,it ONLY worksfor43minand30secondsto10km's.Pythonshouldhaveawaytodothistheproperway. Inordertodothistheproperway,apersonmustdosomethinglikethis. 43*60>converttheminutestoseconds. 2580+30>addtheseconds 2610/10>dividebydistance 261/60>changesecondsintominutes 4.35>istheanswer,nowyoumust .35*60>multiplythenumberafterthedecimalwith60 21seconds.. Endresult=4.21minutesperKM,thistechniqueworksforalldistancesandtimes.
Chapter2
Exercise2.1
Ifyoutypeanintegerwithaleadingzero,youmightgetaconfusingerror:
> > >z i p c o d e=0 2 4 9 2 ^ S y n t a x E r r o r :i n v a l i dt o k e n
Othernumberseemtowork,buttheresultsarebizarre:
> > >z i p c o d e=0 2 1 3 2 > > >p r i n tz i p c o d e 1 1 1 4
en.wikibooks.org/wiki/Think_Python/Print_version 207/282
10/24/13
Exercise2.4
Thevolumeofaspherewithradius ris 4/3 r3. Whatisthevolumeofaspherewithradius5?
> > >p i=3 . 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 1 > > >r=5 > > >4 / 3 * p i * r * * 3#T h i si st h ew r o n ga n s w e r 3 9 2 . 6 9 9 0 8 1 6 9 8 7 2 4 1 1 > > >r=5 . 0#R a d i u sc a nb eaf l o a th e r ea sw e l l ,b u ti sn o t_ n e c e s s a r y _ . > > >4 . 0 / 3 . 0 * p i * r * * 3#U s i n gf l o a t sg i v et h ec o r r e c ta n s w e r 5 2 3 . 5 9 8 7 7 5 5 9 8 2 9 8 8 6 > > >
Supposethecoverpriceofabookis$24.95,butbookstoresgeta40%discount.Shippingcosts$3forthefirstcopyand75centsforeachadditionalcopy. Whatisthetotalwholesalecostfor60copies?
$ 2 4 . 9 5 $ 9 . 9 8 $ 1 4 . 9 7 6 0 $ 8 9 8 . 2 0 C o s t D i s c o u n tp e rb o o k C o s tp e rb o o ka f t e rd i s c o u n t T o t a ln u m b e ro fb o o k s T o t a lc o s tn o ti n cd e l i v e r y
$ 3 . 0 0 F i r s tb o o kd e l i v e r y 5 9 R e m a i n i n gb o o k s
en.wikibooks.org/wiki/Think_Python/Print_version 208/282
10/24/13
Chapter3
Exercise3.3
Pythonprovidesabuiltinfunctioncalled lenthatreturnsthelengthofastring,sothevalueoflen('allen')is5.Writeafunctionnamedright_justifythattakesa stringnamed sasaparameterandprintsthestringwithenoughleadingspacessothatthelastletterofthestringisincolumn70ofthedisplay.
> > >d e fr i g h t _ j u s t i f y ( s ) : . . . p r i n t( '' * ( 7 0 l e n ( s ) ) + s ) . . . > > >r i g h t _ j u s t i f y ( ' a l l e n ' ) a l l e n > > >
Exercise3.5
en.wikibooks.org/wiki/Think_Python/Print_version 209/282
10/24/13
Youcanseemysolutionat[http://thinkpython.com/code/grid.py].
" " " S o l u t i o nt oE x e r c i s eX . Xo np a g eXo fT h i n kP y t h o n A l l e nB .D o w n e y " " " #h e r ei sam o s t l y s t r a i g h t f o r w a r ds o l u t i o nt ot h e #t w o b y t w ov e r s i o no ft h eg r i d . d e fd o _ t w i c e ( f ) : f ( ) f ( ) d e fd o _ f o u r ( f ) : d o _ t w i c e ( f ) d o _ t w i c e ( f ) d e fp r i n t _ b e a m ( ) : p r i n t' +---' , d e fp r i n t _ p o s t ( ) : p r i n t' | ' , d e fp r i n t _ b e a m s ( ) : d o _ t w i c e ( p r i n t _ b e a m ) p r i n t' + ' d e fp r i n t _ p o s t s ( ) : d o _ t w i c e ( p r i n t _ p o s t ) p r i n t' | ' d e fp r i n t _ r o w ( ) : p r i n t _ b e a m s ( ) d o _ f o u r ( p r i n t _ p o s t ) d e fp r i n t _ g r i d ( ) : d o _ t w i c e ( p r i n t _ r o w ) p r i n t _ b e a m s ( ) p r i n t _ g r i d ( ) _ _ _ _ _ _ _ _ _ _ _ _ # a n o t h e rs o l u t i o n d e fd o _ t w i c e ( f ) : f ( ) f ( ) d e fd o _ f o u r ( f ) : d o _ t w i c e ( f ) d o _ t w i c e ( f ) d e fp r i n t _ c o l u m n ( ) :
en.wikibooks.org/wiki/Think_Python/Print_version 210/282
10/24/13
d e fp r i n t _ r o w s ( ) : d o _ f o u r ( p r i n t _ r o w ) d e fd o _ b l o c k ( ) : p r i n t _ c o l u m n ( ) p r i n t _ r o w s ( ) d e fp r i n t _ b l o c k ( ) : d o _ t w i c e ( d o _ b l o c k ) p r i n t _ c o l u m n ( ) p r i n t _ b l o c k ( ) # n a t h a nm o s e s g o n z a l e s _ _ _ _ _ _ _ _ _ #h e r ei sal e s s s t r a i g h t f o r w a r ds o l u t i o nt ot h e #f o u r b y f o u rg r i d d e fo n e _ f o u r _ o n e ( f ,g ,h ) : f ( ) d o _ f o u r ( g ) h ( ) d e fp r i n t _ p l u s ( ) : p r i n t' + ' , d e fp r i n t _ d a s h ( ) : p r i n t' ' , d e fp r i n t _ b a r ( ) : p r i n t' | ' , d e fp r i n t _ s p a c e ( ) : p r i n t'' , d e fp r i n t _ e n d ( ) : p r i n t d e fn o t h i n g ( ) : " d on o t h i n g " d e fp r i n t 1 b e a m ( ) : o n e _ f o u r _ o n e ( n o t h i n g ,p r i n t _ d a s h ,p r i n t _ p l u s ) d e fp r i n t 1 p o s t ( ) : o n e _ f o u r _ o n e ( n o t h i n g ,p r i n t _ s p a c e ,p r i n t _ b a r ) d e fp r i n t 4 b e a m s ( ) : o n e _ f o u r _ o n e ( p r i n t _ p l u s ,p r i n t 1 b e a m ,p r i n t _ e n d )
en.wikibooks.org/wiki/Think_Python/Print_version 211/282
10/24/13
d e fp r i n t 4 p o s t s ( ) : o n e _ f o u r _ o n e ( p r i n t _ b a r ,p r i n t 1 p o s t ,p r i n t _ e n d ) d e fp r i n t _ r o w ( ) : o n e _ f o u r _ o n e ( n o t h i n g ,p r i n t 4 p o s t s ,p r i n t 4 b e a m s ) d e fp r i n t _ g r i d ( ) : o n e _ f o u r _ o n e ( p r i n t 4 b e a m s ,p r i n t _ r o w ,n o t h i n g ) p r i n t _ g r i d ( ) c o m m e n t=" " " A f t e rw r i t i n gad r a f to ft h e4 x 4g r i d ,In o t i c e dt h a tm a n yo ft h e f u n c t i o n sh a dt h es a m es t r u c t u r e :t h e yw o u l dd os o m e t h i n g ,d o s o m e t h i n ge l s ef o u rt i m e s ,a n dt h e nd os o m e t h i n ge l s eo n c e . S oIw r o t eo n e _ f o u r _ o n e ,w h i c ht a k e st h r e ef u n c t i o n sa sa r g u m e n t s ;i t c a l l st h ef i r s to n eo n c e ,t h e nu s e sd o _ f o u rt oc a l lt h es e c o n do n e f o u rt i m e s ,t h e nc a l l st h et h i r d . T h e nIr e w r o t ep r i n t 1 b e a m ,p r i n t 1 p o s t ,p r i n t 4 b e a m s ,p r i n t 4 p o s t s , p r i n t _ r o wa n dp r i n t _ g r i du s i n go n e _ f o u r _ o n e . P r o g r a m m i n gi sa ne x p l o r a t o r yp r o c e s s . W r i t i n gad r a f to fap r o g r a m o f t e ng i v e sy o ui n s i g h ti n t ot h ep r o b l e m ,w h i c hm i g h tl e a dy o ut o r e w r i t et h ec o d et or e f l e c tt h es t r u c t u r eo ft h es o l u t i o n . -A l l e n " " " p r i n tc o m m e n t
Chapter9
Exercise9.1
f i n=o p e n ( ' w o r d s . t x t ' ) f o rl i n ei nf i n : w o r d=l i n e . s t r i p ( ) i fl e n ( w o r d )> =2 0 : p r i n t( w o r d )
Chapter10
Exercise10.1
Writeafunctionthattakesalistofnumbersandreturnsthecumulativesumthatis,anewlistwheretheithelementisthesumofthefirsti+1elementsfrom theoriginallist.Forexample,thecumulativesumof[1,2,3]is[1,3,6].
en.wikibooks.org/wiki/Think_Python/Print_version 212/282
10/24/13
Exercise10.2
Writeafunctioncalledchopthattakesalistandmodifiesit,removingthefirstandlastelements,andreturnsNone.
> > >d e fc h o p ( x ) : d e lx [ : 1 ] d e lx [ 1 : ]
Thenwriteafunctioncalledmiddlethattakesalistandreturnsanewlistthatcontainsallbutthefirstandlastelements.
> > >d e fm i d d l e ( x ) : r e s=[ ] i=1 w h i l ei< =l e n ( x ) 2 : r e s . a p p e n d ( x [ i ] ) i+ =1 r e t u r nr e s
Thiscanalsobedonesimplywithaslice.
> > >d e fm i d d l e ( x ) : r e t u r nx [ 1 : 1 ]
Chapter11
Exercise11.1
Writeafunctionthatreadsthewordsinwords.txtandstoresthemaskeysinadictionary.Itdoesntmatterwhatthevaluesare.Thenyoucanusethein operatorasafastwaytocheckwhetherastringisinthedictionary.
e n g l i s h d i c t i o n a r y=d i c t ( )
en.wikibooks.org/wiki/Think_Python/Print_version 213/282
10/24/13
Exercise11.2
d e fh i s t o g r a m ( s ) : d=d i c t ( ) f o rci ns : d [ c ]=1+d . g e t ( c ,0 ) r e t u r nd
Exercise11.3
Dictionarieshaveamethodcalledkeysthatreturnsthekeysofthedictionary,innoparticularorder,asalist.Modifyprint_histtoprintthekeysandtheir valuesinalphabeticalorder.
v={ ' p ':1 ,' a ':1 ,' r ':2 ,' o ':1 ,' t ':1 } d e fp r i n t _ h i s t ( h ) : x=h . k e y s ( ) y=l i s t ( x ) y . s o r t ( ) f o rci ny : p r i n t ( c ,h [ c ] )
Exercise11.4
d e fr e v e r s e _ l o o k u p ( d , v ) : l=l i s t ( ) f o rci nd : i fd [ c ]= =v : l . a p p e n d ( c ) r e t u r nl
Chapter12
Exercise12.1
en.wikibooks.org/wiki/Think_Python/Print_version 214/282
10/24/13
or
d e fs u m a l l ( * t ) : x=0 f o rii nr a n g e ( l e n ( t ) ) : x+ =t [ i ] r e t u r nx
or
d e fs u m a l l ( * a r g s ) : t=l i s t ( a r g s ) r e t u r ns u m ( t )
Exercise12.2
i m p o r tr a n d o m d e fs o r t _ b y _ l e n g t h ( w o r d s ) : t=[ ] f o rw o r di nw o r d s : t . a p p e n d ( ( l e n ( w o r d ) , w o r d ) ) t . s o r t ( r e v e r s e = T r u e ) r e s=[ ] f o rl e n g t h ,w o r di nt : r e s . a p p e n d ( w o r d ) i = 0 f i n a l=[ ] w h i l ei< =l e n ( r e s ) 2 : i fl e n ( r e s [ i ] )= =l e n ( r e s [ i + 1 ] ) : y _ l i s t=[ r e s [ i ] ,r e s [ i + 1 ] ] r a n d o m . s h u f f l e ( y _ l i s t ) f i n a l=f i n a l+y _ l i s t i+ =2 e l s e : f i n a l . a p p e n d ( r e s [ i ] ) i+ =1 i fi= =l e n ( r e s ) 1 : f i n a l . a p p e n d ( r e s [ i ] ) r e t u r nf i n a l
en.wikibooks.org/wiki/Think_Python/Print_version 215/282
10/24/13
or
f r o mr a n d o mi m p o r ts h u f f l e d e fs o r t _ b y _ l e n g t h ( w o r d s ) : r=[ ] d=d i c t ( ) f o rw o r di nw o r d s : d . s e t d e f a u l t ( l e n ( w o r d ) ,[ ] ) . a p p e n d ( w o r d ) f o rk e yi ns o r t e d ( d ,r e v e r s e = T r u e ) : i fl e n ( d [ k e y ] )>1 : s h u f f l e ( d [ k e y ] ) r . e x t e n d ( d [ k e y ] ) r e t u r nr
Exercise12.3
i m p o r ts t r i n g d e fm o s t _ f r e q u e n t ( s ) : d=d i c t ( ) i n v=d i c t ( ) f o rc h a ri ns : i fc h a ri ns t r i n g . a s c i i _ l e t t e r s : l e t t e r=c h a r . l o w e r ( ) d [ l e t t e r ]=d . g e t ( l e t t e r ,0 )+1 f o rl e t t e r ,f r e qi nd . i t e m s ( ) : i n v . s e t d e f a u l t ( f r e q ,[ ] ) . a p p e n d ( l e t t e r ) f o rf r e qi ns o r t e d ( i n v ,r e v e r s e = T r u e ) : p r i n t ( ' { : . 2 % } : ' . f o r m a t ( f r e q / ( s u m ( l i s t ( i n v ) * l e n ( i n v [ f r e q ] ) ) ) ) ,' ,' . j o i n ( i n v [ f r e q ] ) )
Chapter13
Exercise13.7
f r o ms t r i n gi m p o r tp u n c t u a t i o n ,w h i t e s p a c e ,d i g i t s f r o mr a n d o mi m p o r tr a n d i n t f r o mb i s e c ti m p o r tb i s e c t _ l e f t d e fp r o c e s s _ f i l e ( f i l e n a m e ) : h=d i c t ( ) f p=o p e n ( f i l e n a m e ) f o rl i n ei nf p : p r o c e s s _ l i n e ( l i n e ,h )
en.wikibooks.org/wiki/Think_Python/Print_version 216/282
10/24/13
r e t u r nh d e fp r o c e s s _ l i n e ( l i n e ,h ) : l i n e=l i n e . r e p l a c e ( ' ' ,'' ) f o rw o r di nl i n e . s p l i t ( ) : w o r d=w o r d . s t r i p ( p u n c t u a t i o n+w h i t e s p a c e+d i g i t s ) w o r d=w o r d . l o w e r ( ) i fw o r d! =' ' : h [ w o r d ]=h . g e t ( w o r d ,0 )+1 h i s t=p r o c e s s _ f i l e ( ' e m m a . t x t ' ) d e fc u m _ s u m ( l i s t _ o f _ n u m b e r s ) : c u m _ l i s t=[ ] f o ri ,e l e mi ne n u m e r a t e ( l i s t _ o f _ n u m b e r s ) : i fi= =0 : c u m _ l i s t . a p p e n d ( e l e m ) e l s e : c u m _ l i s t . a p p e n d ( c u m _ l i s t [ i 1 ]+e l e m ) r e t u r nc u m _ l i s t d e fr a n d o m _ w o r d ( h ) : w o r d _ l i s t=l i s t ( h . k e y s ( ) ) n u m _ l i s t=[ ] f o rw o r di nw o r d _ l i s t : n u m _ l i s t . a p p e n d ( h [ w o r d ] ) c u m _ l i s t=c u m _ s u m ( n u m _ l i s t ) i=r a n d i n t ( 1 ,c u m _ l i s t [ 1 ] ) p o s=b i s e c t _ l e f t ( c u m _ l i s t ,i ) r e t u r nw o r d _ l i s t [ p o s ] p r i n t ( r a n d o m _ w o r d ( h i s t ) )
Chapter14
Exercise14.3
i m p o r ts h e l v e d e fd i c t _ o f _ s i g n a t u r e s _ a n d _ w o r d s ( f i l e n a m e = ' w o r d s . t x t ' ) : d=d i c t ( ) f o rl i n ei no p e n ( f i l e n a m e ) : w o r d=l i n e . l o w e r ( ) . s t r i p ( ) s i g n a t u r e=' ' . j o i n ( s o r t e d ( w o r d ) ) d . s e t d e f a u l t ( s i g n a t u r e ,[ ] ) . a p p e n d ( w o r d ) r e t u r nd d e fd b _ o f _ a n a g r a m s ( f i l e n a m e = ' a n a g r a m s ' ,d = d i c t _ o f _ s i g n a t u r e s _ a n d _ w o r d s ( ) ) : d b=s h e l v e . o p e n ( f i l e n a m e ) f o rk e y ,v a l u e si nd . i t e m s ( ) : i fl e n ( v a l u e s ) > 1 : f o ri n d e x ,v a l u ei ne n u m e r a t e ( v a l u e s ) :
en.wikibooks.org/wiki/Think_Python/Print_version 217/282
10/24/13
d b [ v a l u e ] = v a l u e s [ : i n d e x ] + v a l u e s [ i n d e x + 1 : ] d b . c l o s e ( ) d e fp r i n t _ c o n t e n t s _ o f _ d b ( f i l e n a m e = ' a n a g r a m s ' ) : d b=s h e l v e . o p e n ( f i l e n a m e ,f l a g = ' r ' ) f o rk e yi ns o r t e d ( d b ) : p r i n t ( k e y . r j u s t ( 1 2 ) ,' \ t < = = > \ t ' ,' ,' . j o i n ( d b [ k e y ] ) ) d b . c l o s e ( ) d b _ o f _ a n a g r a m s ( ) p r i n t _ c o n t e n t s _ o f _ d b ( )
Exercise14.5
#R e p l a c eu r l l i b . r e q u e s tw i t hu r l l i bi fy o uu s eP y t h o n2 . #Iw o u l dl o v et os e eam o r ee l e g a n ts o l u t i o nf o rt h i se x e r c i s e ,p o s s i b l yb ys o m e o n ew h ou n d e r s t a n d sh t m l . i m p o r tu r l l i b . r e q u e s t d e fc h e c k ( z i p _ c o d e ) : i fz i p _ c o d e= =' d o n e ' : r e t u r nb r e a k i fl e n ( z i p _ c o d e )! =5 : p r i n t ( ' \ n T h ez i pc o d em u s th a v ef i v ed i g i t s ! ' ) r e t u r nc o n t i n u e d e fg e t _ h t m l ( z i p _ c o d e ) : g i b b e r i s h=u r l l i b . r e q u e s t . u r l o p e n ( ' h t t p : / / w w w . u s z i p . c o m / z i p / '+z i p _ c o d e ) l e s s _ g i b=g i b b e r i s h . r e a d ( ) . d e c o d e ( ' u t f 8 ' ) r e t u r nl e s s _ g i b d e fe x t r a c t _ t r u t h ( c o d e ,k e y ,d e l i m i t e r ) : p o s=c o d e . f i n d ( k e y )+l e n ( k e y ) n e a r l y _ t r u e=c o d e [ p o s : p o s + 4 0 ] t r u t h=n e a r l y _ t r u e . s p l i t ( d e l i m i t e r ) [ 0 ] r e t u r nt r u t h w h i l eT r u e : z i p _ c o d e=i n p u t ( ' P l e a s et y p eaz i pc o d e( 5d i g i t s )o r" d o n e "i fw a n tt os t o p : \ n ' ) c h e c k ( z i p _ c o d e ) c o d e=g e t _ h t m l ( z i p _ c o d e ) i n v a l i d _ k e y=' ( 0r e s u l t s ) ' i fi n v a l i d _ k e yi nc o d e : p r i n t ( ' \ n N o tav a l i dz i pc o d e . ' ) c o n t i n u e n a m e _ k e y=' z i pc o d eo f< s t r o n g > ' n a m e _ d e l=' < ' n a m e=e x t r a c t _ t r u t h ( c o d e ,n a m e _ k e y ,n a m e _ d e l )
en.wikibooks.org/wiki/Think_Python/Print_version 218/282
10/24/13
p o p _ k e y=' P o p u l a t i o n : < / b > < / t d > < t d > ' p o p _ d e l='< ' n a m e=e x t r a c t _ t r u t h ( c o d e ,p o p _ k e y ,p o p _ d e l ) i fn o t1<l e n ( p o p )<9 : p o p=' n o ta v a i l a b l e ' p r i n t ( ' \ n '+n a m e ) p r i n t ( ' P o p u l a t i o n : ' ,p o p ,' \ n ' )
Chapter15
Exercise15.1
i m p o r tm a t h c l a s sP o i n t ( o b j e c t ) : " " " r e p r e s e n t sap o i n ti n2 Ds p a c e " " " d e fd i s t a n c e ( p 1 ,p 2 ) : d i s t a n c e=m a t h . s q r t ( ( p 2 . x-p 1 . x ) * * 2+( p 2 . y-p 1 . y ) * * 2 ) r e t u r nd i s t a n c e p 1=P o i n t ( ) p 2=P o i n t ( ) p 1 . x=3 p 1 . y=2 p 2 . x=4 p 2 . y=3 p r i n t ( d i s t a n c e ( p 1 ,p 2 ) )
Chapter16
Exercise16.1
d e fp r i n t _ t i m e ( t ) : p r i n t' % . 2 d : % . 2 d : % . 2 d '%( t . h o u r ,t . m i n u t e ,t . s e c o n d )
or
#S o l u t i o nf o rP y t h o n 3 #M o r eo ns t r i n gf o r m a t t i n g :h t t p : / / d o c s . p y t h o n . o r g / p y 3 k / l i b r a r y / s t r i n g . h t m l # f o r m a t s p e c
en.wikibooks.org/wiki/Think_Python/Print_version 219/282
10/24/13
Exercise16.2
d e fi s _ a f t e r ( t 1 ,t 2 ) : r e t u r n( t 1 . h o u r ,t 1 . m i n u t e ,t 1 . s e c o n d )>( t 2 . h o u r ,t 2 . m i n u t e ,t 2 . s e c o n d )
Exercise16.3
#C o m m e n tn o tb yt h ea u t h o r :T h i sw i l lg i v eaw r o n gr e s u l t ,i f( t i m e . s e c o n d+s e c o n d s%6 0 )>6 0 d e fi n c r e m e n t ( t i m e ,s e c o n d s ) : n=s e c o n d s / 6 0 t i m e . s e c o n d+ =s e c o n d s-6 0 . 0 * n t i m e . m i n u t e+ =n m=t i m e . m i n u t e / 6 0 t i m e . m i n u t e=m * 6 0 t i m e . h o u r+ =m
or
#S o l u t i o nf o rP y t h o n 3 #R e p l a c e' / / 'b y' / 'f o rP y t h o n 2 d e fi n c r e m e n t ( t i m e ,s e c o n d s ) : t i m e . s e c o n d+ =s e c o n d s t i m e . m i n u t e+ =t i m e . s e c o n d / / 6 0 t i m e . h o u r+ =t i m e . m i n u t e / / 6 0 t i m e . s e c o n d% =6 0 t i m e . m i n u t e% =6 0 t i m e . h o u r% =2 4
Exercise16.4
#S o l u t i o nf o rP y t h o n 3 #R e p l a c e' / / 'b y' / 'f o rP y t h o n 2 f r o mc o p yi m p o r td e e p c o p y d e fi n c r e m e n t ( t i m e ,s e c o n d s ) :
en.wikibooks.org/wiki/Think_Python/Print_version 220/282
10/24/13
r=d e e p c o p y ( t i m e ) r . s e c o n d+ =s e c o n d s r . m i n u t e+ =r . s e c o n d / / 6 0 r . h o u r+ =r . m i n u t e / / 6 0 r . s e c o n d% =6 0 r . m i n u t e% =6 0 r . h o u r% =2 4 r e t u r nr
Exercise16.5
c l a s sT i m e ( o b j e c t ) : " " " r e p r e s e n t st h et i m eo fd a y . a t t r i b u t e s :h o u r ,m i n u t e ,s e c o n d " " " t i m e=T i m e ( ) t i m e . h o u r=1 1 t i m e . m i n u t e=5 9 t i m e . s e c o n d=3 0 d e ft i m e _ t o _ i n t ( t i m e ) : m i n u t e s=t i m e . h o u r*6 0+t i m e . m i n u t e s e c o n d s=m i n u t e s*6 0+t i m e . s e c o n d r e t u r ns e c o n d s d e fi n t _ t o _ t i m e ( s e c o n d s ) : t i m e=T i m e ( ) m i n u t e s ,t i m e . s e c o n d=d i v m o d ( s e c o n d s ,6 0 ) t i m e . h o u r ,t i m e . m i n u t e=d i v m o d ( m i n u t e s ,6 0 ) r e t u r nt i m e d e fi n c r e m e n t ( t i m e ,a d d t i m e ) : s e c o n d s=t i m e _ t o _ i n t ( t i m e ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s+a d d t i m e ) d e fp r i n t _ t i m e( x ) : p r i n t' T h et i m ei s% . 2 d:% . 2 d:% . 2 d '%( x . h o u r ,x . m i n u t e ,x . s e c o n d ) p r i n t _ t i m e( t i m e ) n e w t i m e=i n c r e m e n t( t i m e ,7 0 ) p r i n t _ t i m e( n e w t i m e )
Exercise16.6
d e ft i m e _ t o _ i n t ( t i m e ) : m i n u t e s=t i m e . h o u r*6 0+t i m e . m i n u t e
en.wikibooks.org/wiki/Think_Python/Print_version 221/282
10/24/13
Exercise16.7
WriteaclassdefinitionforaDateobjectthathasattributes day, monthand year.Writeafunctioncalled increment_datethattakesaDateobject, date,andan integer, n,andreturnsanewDateobjectthatrepresentstheday ndaysafter date.Hint:ThirtydayshathSeptember...Challenge:doesyourfunctiondeal withleapyearscorrectly?See wikipedia.org/wiki/Leap_year.
c l a s sD a t e ( o b j e c t ) : " " " r e p r e s e n t sad a t e . a t t r i b u t e s :d a y ,m o n t h ,y e a r " " " d e fp r i n t _ d a t e ( d a t e ) : #G e r m a nd a t ef o r m a t p r i n t ( ' { } . { } . { } ' . f o r m a t ( d a t e . d a y ,d a t e . m o n t h ,d a t e . y e a r ) ) d e fi s _ l e a p _ y e a r ( y e a r ) : #h t t p : / / e n . w i k i p e d i a . o r g / w i k i / L e a p _ y e a r # A l g o r i t h m i fy e a r%4= =0 : i fy e a r%1 0 0= =0 : i fy e a r%4 0 0= =0 : r e t u r nT r u e r e t u r nF a l s e r e t u r nT r u e r e t u r nF a l s e d e fm o n t h _ l i s t ( y e a r ) : i fi s _ l e a p _ y e a r ( y e a r ) : r e t u r n[ 3 1 ,2 9 ,3 1 ,3 0 ,3 1 ,3 0 ,3 1 ,3 1 ,3 0 ,3 1 ,3 0 ,3 1 ] r e t u r n[ 3 1 ,2 8 ,3 1 ,3 0 ,3 1 ,3 0 ,3 1 ,3 1 ,3 0 ,3 1 ,3 0 ,3 1 ] d e fd a y s _ o f _ y e a r ( y e a r ) : i fi s _ l e a p _ y e a r ( y e a r ) : r e t u r n3 6 6
en.wikibooks.org/wiki/Think_Python/Print_version 222/282
10/24/13
r e t u r n3 6 5 d e fd a t e _ t o _ i n t ( d a t e ) : d a y s=0 f o ry e a ri nr a n g e ( 1 ,d a t e . y e a r ) : d a y s+ =d a y s _ o f _ y e a r ( y e a r ) m o n t h _ d a y s=m o n t h _ l i s t ( d a t e . y e a r ) f o rm o n t hi nr a n g e ( 1 ,d a t e . m o n t h ) : d a y s+ =m o n t h _ d a y s [ m o n t h-1 ] d a y s+ =d a t e . d a y-1 r e t u r nd a y s d e fi n t _ t o _ d a t e ( d a y s ) : d a t e=D a t e ( ) d a t e . y e a r=1 n e x t _ d a y s=3 6 5 w h i l ed a y s> =n e x t _ d a y s : d a t e . y e a r+ =1 d a y s=n e x t _ d a y s n e x t _ d a y s=d a y s _ o f _ y e a r ( d a t e . y e a r ) d a t e . m o n t h=1 n e x t _ d a y s=3 1 m o n t h _ d a y s=m o n t h _ l i s t ( d a t e . y e a r ) w h i l ed a y s> =n e x t _ d a y s : d a t e . m o n t h+ =1 d a y s=n e x t _ d a y s n e x t _ d a y s=m o n t h _ d a y s [ d a t e . m o n t h-1 ] d a t e . d a y=d a y s+1 r e t u r nd a t e d e fi n c r e m e n t _ d a t e ( d a t e ,n ) : d a y s=d a t e _ t o _ i n t ( d a t e ) r e t u r ni n t _ t o _ d a t e ( d a y s+n ) d 1=D a t e ( ) d 1 . d a y ,d 1 . m o n t h ,d 1 . y e a r=8 ,3 ,2 0 1 2 p r i n t _ d a t e ( d 1 ) d 2=i n c r e m e n t _ d a t e ( d 1 ,7 ) p r i n t _ d a t e ( d 2 )
Exercise16.8
1.Usethe datetimemoduletowriteaprogramthatgetsthecurrentdateandprintsthedayoftheweek.
f r o md a t e t i m ei m p o r td a t e d e fc u r r e n t _ w e e k d a y ( ) :
en.wikibooks.org/wiki/Think_Python/Print_version 223/282
10/24/13
i=d a t e . t o d a y ( ) . w e e k d a y ( ) p r i n t ( [ ' M o n d a y ' ,' T u e s d a y ' ,' W e d n e s d a y ' ,' T h u r s d a y ' ,' F r i d a y ' ,' S a t u r d a y ' ,' S u n d a y ' ] [ i ] ) c u r r e n t _ w e e k d a y ( )
2.Writeaprogramthattakesabirthdayasinputandprintstheusersageandthenumberofdays,hours,minutesandsecondsuntiltheirnextbirthday.
#P y t h o n 3s o l u t i o n .R e p l a c e" i n p u t "b y" r a w _ i n p u t "f o rP y t h o n 2 . f r o md a t e t i m ei m p o r td a t e t i m e d e ft i m e _ u n t i l _ b i r t h d a y ( ) : d o b _ i n p u t=i n p u t ( ( ' P l e a s ee n t e rt h ed a t eo fy o u rb i r t hi n' ' t h ef o r m a t" m m / d d / y y y y " :' ) ) d o b=d a t e t i m e . s t r p t i m e ( d o b _ i n p u t ,' % m / % d / % Y ' ) n o w=d a t e t i m e . n o w ( ) i fn o w>d a t e t i m e ( n o w . y e a r ,d o b . m o n t h ,d o b . d a y ) : a g e=n o w . y e a r-d o b . y e a r n e x t _ y e a r=T r u e e l s e : a g e=n o w . y e a r-d o b . y e a r-1 n e x t _ y e a r=F a l s e t i m e _ t o _ b i r t h d a y=d a t e t i m e ( n o w . y e a r+n e x t _ y e a r , d o b . m o n t h ,d o b . d a y )-n o w d a y s=t i m e _ t o _ b i r t h d a y . d a y s h o u r s ,r e m a i n d e r=d i v m o d ( t i m e _ t o _ b i r t h d a y . s e c o n d s ,3 6 0 0 ) m i n u t e s ,s e c o n d s=d i v m o d ( r e m a i n d e r ,6 0 ) p r i n t ( " \ n Y o ua r e{ }y e a r so l d . " . f o r m a t ( a g e ) ) p r i n t ( ( " Y o uh a v e{ 0 }d a y s ,{ 1 }h o u r s ,{ 2 }m i n u t e sa n d{ 3 }" " s e c o n d sl e f tu n t i ly o u rn e x tb i r t h d a y . " ) . f o r m a t ( d a y s ,h o u r s ,m i n u t e s ,s e c o n d s ) ) t i m e _ u n t i l _ b i r t h d a y ( )
Chapter17
Exercise17.8
2.
f r o mv i s u a li m p o r ts c e n e ,s p h e r e s c e n e . r a n g e=( 2 5 6 ,2 5 6 ,2 5 6 ) s c e n e . c e n t e r=( 1 2 8 ,1 2 8 ,1 2 8 ) t=r a n g e ( 0 ,2 5 6 ,5 1 ) f o rxi nt : f o ryi nt : f o rzi nt : p o s=x ,y ,z
en.wikibooks.org/wiki/Think_Python/Print_version 224/282
10/24/13
c o l o r=( x / 2 5 5 . ,y / 2 5 5 . ,z / 2 5 5 . ) s p h e r e ( p o s = p o s ,r a d i u s = 1 0 ,c o l o r = c o l o r )
Chapter3.5
calculator
# r e c u r s i o no rr e c u r s i v e p r i n t" \ n I N D E X \ n " " \ n C = 1f o ra d d i t i o n \ n " " \ n C = 2f o rs u b s t r a c t i o n \ n " " \ n C = 3f o rm u l t i p l i c a t i o n \ n " " \ n C = 4f o rd i v i s i o n \ n " " \ n C = 5f o rt of i n dm o d u l u s \ n " " \ n C = 6t of i n df a c t o r i a l \ n " C = i n p u t ( " E n t e ry o u rc h o i c eh e r e :" ) d e fa d d ( x , y ) : c = x + y
en.wikibooks.org/wiki/Think_Python/Print_version 225/282
10/24/13
p r i n tx , " + " , y , " = " , c d e fs u b ( x , y ) : c = x y p r i n tx , " " , y , " = " , c d e fm u l ( x , y ) : c = x * y p r i n tx , " * " , y , " = " , c d e fd i v ( x , y ) : c = x / y p r i n tx , " / " , y , " = " , c d e fm o d ( x , y ) : c = x % y p r i n tx , " % " , y , " = " , c i fC = = 6 : d e ff ( n ) : i fn = = 1 : p r i n tn r e t u r nn e l s e : p r i n tn , " * " , r e t u r nn * f ( n 1 ) n = i n p u t ( " e n t e ry o u rn oh e r e :" ) p r i n tf ( n ) i fC = = 1 : a = i n p u t ( " E n t e ry o u rf i r s tn oh e r e :" ) b = i n p u t ( " E n t e ry o u rs e c o n dn oh e r e :" ) a d d ( a , b ) e l i fC = = 2 : a = i n p u t ( " E n t e ry o u rf i r s tn oh e r e :" ) b = i n p u t ( " E n t e ry o u rs e c o n dn oh e r e :" ) s u b ( a , b ) e l i fC = = 3 : a = i n p u t ( " E n t e ry o u rf i r s tn oh e r e :" ) b = i n p u t ( " E n t e ry o u rs e c o n dn oh e r e :" ) m u l ( a , b ) e l i fC = = 4 : a = i n p u t ( " E n t e ry o u rf i r s tn oh e r e :" ) b = i n p u t ( " E n t e ry o u rs e c o n dn oh e r e :" ) d i v ( a , b ) e l i fC = = 5 : a = i n p u t ( " E n t e ry o u rf i r s tn oh e r e :" ) b = i n p u t ( " E n t e ry o u rs e c o n dn oh e r e :" ) m o d ( a , b )
palindrome
d e ff i r s t ( w o r d ) : r e t u r nw o r d [ 0 ] d e fl a s t ( w o r d ) : r e t u r nw o r d [ 1 ] d e fm i d d l e ( w o r d ) : r e t u r nw o r d [ 1 : 1 ] d e fp a l i n d r o m e ( w o r d ) :
en.wikibooks.org/wiki/Think_Python/Print_version 226/282
10/24/13
sumofalldigits
d e fs u m _ o f _ n _ n u m b e r s ( n u m b e r ) : i f ( n u m b e r = = 0 ) : r e t u r n0 e l s e : r e t u r nn u m b e r+s u m _ o f _ n _ n u m b e r s ( n u m b e r 1 ) n u m=r a w _ i n p u t ( " E n t e ran u m b e r : " ) n u m = i n t ( n u m ) s u m=s u m _ o f _ n _ n u m b e r s ( n u m ) p r i n ts u m # # # a n o t h e ra n s w e ri nc a s eo fw h i l el o o p s d e fs u m _ o f _ D i g i t s ( n u m b e r ) : s u m = 0 w h i l en u m b e r > 0 : d i g i t = n u m b e r % 1 0 s u m = s u m + d i g i t n u m b e r = n u m b e r / 1 0 r e t u r ns u m n u m = r a w _ i n p u t ( " e n t e rt h en u m b e r " ) n u m = i n t ( n u m ) s u m _ o f _ d i g i t s = s u m _ o f _ D i g i t s ( n u m ) p r i n ts u m _ o f _ d i g i t s
Exercise18.5
c l a s sC a r d ( o b j e c t ) : s u i t _ n a m e s=[ ' C l u b s ' ,' D i a m o n d s ' ,' H e a r t s ' ,' S p a d e s ' ] r a n k _ n a m e s=[ N o n e ,' A c e ' ,' 2 ' ,' 3 ' ,' 4 ' ,' 5 ' ,' 6 ' ,' 7 ' , ' 8 ' ,' 9 ' ,' 1 0 ' ,' J a c k ' ,' Q u e e n ' ,' K i n g ' ] d e f_ _ i n i t _ _ ( s e l f ,s u i t=0 ,r a n k=2 ) : s e l f . s u i t=s u i t s e l f . r a n k=r a n k
en.wikibooks.org/wiki/Think_Python/Print_version 227/282
10/24/13
d e f_ _ s t r _ _ ( s e l f ) : r e t u r n' % so f% s '%( C a r d . r a n k _ n a m e s [ s e l f . r a n k ] , C a r d . s u i t _ n a m e s [ s e l f . s u i t ] ) d e f_ _ c m p _ _ ( s e l f ,o t h e r ) : c 1=( s e l f . s u i t ,s e l f . r a n k ) c 2=( o t h e r . s u i t ,o t h e r . r a n k ) r e t u r nc m p ( c 1 ,c 2 ) d e fi s _ v a l i d ( s e l f ) : r e t u r ns e l f . r a n k>0 c l a s sD e c k ( o b j e c t ) : d e f_ _ i n i t _ _ ( s e l f ,l a b e l=' D e c k ' ) : s e l f . l a b e l=l a b e l s e l f . c a r d s=[ ] f o rii nr a n g e ( 4 ) : f o rki nr a n g e ( 1 ,1 4 ) : c a r d=C a r d ( i ,k ) s e l f . c a r d s . a p p e n d ( c a r d ) d e f_ _ s t r _ _ ( s e l f ) : r e s=[ ] f o rc a r di ns e l f . c a r d s : r e s . a p p e n d ( s t r ( c a r d ) ) p r i n ts e l f . l a b e l r e t u r n' \ n ' . j o i n ( r e s ) d e fd e a l _ c a r d ( s e l f ) : r e t u r ns e l f . c a r d s . p o p ( 0 ) d e fa d d _ c a r d ( s e l f ,c a r d ) : s e l f . c a r d s . a p p e n d ( c a r d ) d e fs h u f f l e ( s e l f ) : i m p o r tr a n d o m r a n d o m . s h u f f l e ( s e l f . c a r d s ) d e fs o r t ( s e l f ) : s e l f . c a r d s . s o r t ( ) d e fm o v e _ c a r d s ( s e l f ,o t h e r ,n u m ) : f o rii nr a n g e ( n u m ) : o t h e r . a d d _ c a r d ( s e l f . d e a l _ c a r d ( ) ) d e fd e a l _ h a n d s ( s e l f ,n u m _ h a n d s ,n u m _ c a r d s ) : i fn u m _ h a n d s * n u m _ c a r d s>5 2 : r e t u r n' N o te n o u g hc a r d s . ' l=[ ] f o rii nr a n g e ( 1 ,n u m _ h a n d s+1 ) : h a n d _ i=H a n d ( ' H a n d% d '%i ) s e l f . m o v e _ c a r d s ( h a n d _ i ,n u m _ c a r d s )
en.wikibooks.org/wiki/Think_Python/Print_version 228/282
10/24/13
l . a p p e n d ( h a n d _ i ) r e t u r nl c l a s sH a n d ( D e c k ) : d e f_ _ i n i t _ _ ( s e l f ,l a b e l=' ' ) : s e l f . c a r d s=[ ] s e l f . l a b e l=l a b e l #1 8 6 ,1 4 : c l a s sP o k e r H a n d ( H a n d ) : d e fs u i t _ h i s t ( s e l f ) : s e l f . s u i t s={ } f o rc a r di ns e l f . c a r d s : s e l f . s u i t s [ c a r d . s u i t ]=s e l f . s u i t s . g e t ( c a r d . s u i t ,0 )+1 r e t u r ns e l f . s u i t s d e fr a n k _ h i s t ( s e l f ) : s e l f . r a n k s={ } f o rc a r di ns e l f . c a r d s : s e l f . r a n k s [ c a r d . r a n k ]=s e l f . r a n k s . g e t ( c a r d . r a n k ,0 )+1 r e t u r ns e l f . r a n k s d e fP ( s e l f ) : s e l f . r a n k _ h i s t ( ) f o rv a li ns e l f . r a n k s . v a l u e s ( ) : i fv a l> =2 : r e t u r nT r u e r e t u r nF a l s e d e fT P ( s e l f ) : s e l f . r a n k _ h i s t ( ) c o u n t=0 f o rv a li ns e l f . r a n k s . v a l u e s ( ) : i fv a l= =4 : r e t u r nT r u e e l i fv a l> =2a n dv a l<4 : c o u n t+ =1 r e t u r nc o u n t> =2 d e fT O A K ( s e l f ) : s e l f . r a n k _ h i s t ( ) f o rv a li ns e l f . r a n k s . v a l u e s ( ) : i fv a l> =3 : r e t u r nT r u e r e t u r nF a l s e d e fS T R s e q ( s e l f ) : s e q=[ ] l=S T R l i s t ( ) s e l f . r a n k _ h i s t ( ) h=s e l f . r a n k s . k e y s ( ) h . s o r t ( ) i fl e n ( h )<5 :
en.wikibooks.org/wiki/Think_Python/Print_version 229/282
10/24/13
r e t u r n[ ] #A c c o u n t sf o rh i g hA c e s : i f1i nh : h . a p p e n d ( 1 ) f o rii nr a n g e ( 5 ,l e n ( h ) + 1 ) : i fh [ i 5 : i ]i nl : s e q . a p p e n d ( h [ i 5 : i ] ) r e t u r ns e q d e fS T R ( s e l f ) : s e q=s e l f . S T R s e q ( ) r e t u r ns e q! =[ ] d e fF L ( s e l f ) : s e l f . s u i t _ h i s t ( ) f o rv a li ns e l f . s u i t s . v a l u e s ( ) : i fv a l> =5 : r e t u r nT r u e r e t u r nF a l s e d e fF H ( s e l f ) : d=s e l f . r a n k _ h i s t ( ) k e y s=d . k e y s ( ) f o rk e yi nk e y s : i fd [ k e y ]> =3 : k e y s . r e m o v e ( k e y ) f o rk e yi nk e y s : i fd [ k e y ]> =2 : r e t u r nT r u e r e t u r nF a l s e d e fF O A K ( s e l f ) : s e l f . r a n k _ h i s t ( ) f o rv a li ns e l f . r a n k s . v a l u e s ( ) : i fv a l> =4 : r e t u r nT r u e r e t u r nF a l s e d e fS F L ( s e l f ) : s e q=s e l f . S T R s e q ( ) i fs e q= =[ ] : r e t u r nF a l s e f o rl i s ti ns e q : l i s t _ s u i t s=[ ] f o ri n d e xi nl i s t : f o rc a r di ns e l f . c a r d s : i fc a r d . r a n k= =i n d e x : l i s t _ s u i t s . a p p e n d ( c a r d . s u i t ) l i s t _ h i s t=h i s t o g r a m ( l i s t _ s u i t s ) f o rk e yi nl i s t _ h i s t . k e y s ( ) : i fl i s t _ h i s t [ k e y ]> =5 : r e t u r nT r u e r e t u r nF a l s e
en.wikibooks.org/wiki/Think_Python/Print_version 230/282
10/24/13
d e fc l a s s i f y ( s e l f ) : s e l f . s c o r e s=[ ] h a n d s=[ ' P a i r ' ,' T w o P a i r ' , ' T h r e eo faK i n d ' ,' S t r a i g h t ' , ' F l u s h ' ,' F u l lH o u s e ' , ' F o u ro faK i n d ' ,' S t r a i g h tF l u s h ' ] i fs e l f . P ( ) : s e l f . s c o r e s . a p p e n d ( 1 ) i fs e l f . T P ( ) : s e l f . s c o r e s . a p p e n d ( 2 ) i fs e l f . T O A K ( ) : s e l f . s c o r e s . a p p e n d ( 3 ) i fs e l f . S T R ( ) : s e l f . s c o r e s . a p p e n d ( 4 ) i fs e l f . F L ( ) : s e l f . s c o r e s . a p p e n d ( 5 ) i fs e l f . F H ( ) : s e l f . s c o r e s . a p p e n d ( 6 ) i fs e l f . F O A K ( ) : s e l f . s c o r e s . a p p e n d ( 7 ) i fs e l f . S F L ( ) : s e l f . s c o r e s . a p p e n d ( 8 ) i fs e l f . s c o r e s! =[ ] : r e t u r nh a n d s [ m a x ( s e l f . s c o r e s ) 1 ] d e fS T R l i s t ( ) : s=[ ] f o rii nr a n g e ( 0 , 9 ) : s . a p p e n d ( r a n g e ( 1 , 1 4 ) [ i : i + 5 ] ) s . a p p e n d ( [ 1 0 , 1 1 , 1 2 , 1 3 , 1 ] ) r e t u r ns d e fh i s t o g r a m ( l ) : d=d i c t ( ) f o rki nr a n g e ( l e n ( l ) ) : d [ l [ k ] ]=1+d . g e t ( l [ k ] , 0 ) r e t u r nd #1 8 6 ,5 : d e fp ( c o n f i g=' ' ,t r i a l s=1 0 0 0 0 ,n=1 ) : " " " E s t i m a t e sp r o b a b i l i t yt h a tt h e n t hd e a l th a n dw i l lb ec o n f i g .Ah a n d c o n s i s t so fs e v e nc a r d s . " " " s u c c e s s e s=0 f o rii nr a n g e ( 1 ,t r i a l s+1 ) : d e c k=D e c k ( ' D e c k% d '%i ) d e c k . s h u f f l e ( ) b o x=H a n d ( ) d e c k . m o v e _ c a r d s ( b o x ,( n 1 ) * 7 ) h a n d=P o k e r H a n d ( ' P o k e rH a n d% d '%i ) d e c k . m o v e _ c a r d s ( h a n d ,7 )
en.wikibooks.org/wiki/Think_Python/Print_version 231/282
10/24/13
AppendixB
ExerciseB.3
Writeafunctioncalled bisectionthattakesasortedlistandatargetvalueandreturnstheindexofthevalueinthelist,ifitsthere,or Noneifitsnot.
f r o mb i s e c ti m p o r tb i s e c t _ l e f t d e fb i s e c t i o n ( s o r t e d _ l i s t ,i t e m ) : i=b i s e c t _ l e f t ( s o r t e d _ l i s t ,i t e m ) i fi<l e n ( s o r t e d _ l i s t )a n ds o r t e d _ l i s t [ i ]= =i t e m : r e t u r ni e l s e : r e t u r nN o n e i f_ _ n a m e _ _= =' _ _ m a i n _ _ ' : a=[ 1 ,2 ,3 ] p r i n t ( b i s e c t i o n ( a ,2 ) ) #e x p e c t1 b=[ 1 ,3 ] p r i n t ( b i s e c t i o n ( b ,2 ) ) #e x p e c tN o n e c=[ 1 ,2 ] p r i n t ( b i s e c t i o n ( c ,3 ) ) #e x p e c tN o n e
Index
en.wikibooks.org/wiki/Think_Python/Print_version 232/282
10/24/13
Index
Ackermanfunction,6.11 literalness,1.4
AttributeError,15.7,A.2.3
localvariable,3.9,3.14
Austin,Jane,13.3
logfunction,3.3
abecedarian,8.3,9.2
logarithm,13.12
absfunction,6.1
logicaloperator,5.2,5.3
absolutepath,14.4,14.11
longinteger,11.7
access,10.2
lookup,11.9
accumulator,10.14
lookup,dictionary,11.3
histogram,13.3
loop,4.2,4.11,7.3,12.5
list,10.7
condition,A.2.2
string,18.5
en.wikibooks.org/wiki/Think_Python/Print_version
event,19.1
233/282
10/24/13
sum,10.7
for,4.2,8.3,10.3
MD5,14.12
looping withdictionaries,11.2
10/24/13
alphabet,4.12
lowlevellanguage,1.1,1.7
alternativeexecution,5.5
ls(Unixcommand),14.8
ambiguity,1.4 Markovanalysis,13.8 anagram,10.15 McCloskey,Robert,8.3 anagramset,12.11,14.7 MD5algorithm,14.12 andoperator,5.3 Menubuttonwidget,19.7 anydbmmodule,14.6 MontyPythonandtheHolyGrail,16.2 appendmethod,10.6,10.12,10.15,18.4,18.6 MP3,14.12 arcfunction,4.3 mappattern,10.7,10.14 argument,3.1,3.5,3.8,3.8,3.14,10.12 mapto,18.1 gather,12.4
en.wikibooks.org/wiki/Think_Python/Print_version
235/282
10/24/13
keyword,4.5,4.11,12.7,19.2
mapping,10.2,10.14,13.8
list,10.12
mashup,13.8
optional,8.8,10.9,11.3
mathfunction,3.3
variablelengthtuple,12.4
maxfunction,12.3,12.4
arithmeticoperator,2.5
dictionary,11
assertstatement,16.5
list,10.2
assignment,2.11,7.1,10.1
set,11
10/24/13
assignmentstatement,2.2
metathesis,12.11
attribute __dict__,17.10
method,8.8,8.12,17.1,17.11
availablecolors,15.9,17.12
close,14.2,14.6,14.8
10/24/13
init,17.5,18.1,18.4,18.7 benchmarking,13.9,13.11 items,12.6 big,hairyexpression,A.3.2 join,10.9,18.5 binding,19.8,19.10 keys,11.2 bingo,12.11 mro,18.9 birthday,16.7 pop,10.8,18.6 birthdayparadox,10.15 radd,17.8 bisectmodule,10.15 read,14.8 bisectionsearch,10.15 readline,9.1,14.8 bisection,debuggingby,7.7 remove,10.8 bitwiseoperator,2.5 replace,13.1 body,3.5,3.14,5.13,7.3 setdefault,11.4
en.wikibooks.org/wiki/Think_Python/Print_version 238/282
10/24/13
booltype,5.2 sort,10.6,10.13,12.7,18.6 booleanexpression,5.2,5.13 split,10.9,12.2 booleanfunction,6.4,16.1 string,8.13 booleanoperator,8.9 strip,9.1,13.1 borrowing,subtractionwith,7.6,16.4 translate,13.1 boundmethod,19.6,19.10 update,12.6 boundingbox,15.9,19.4,19.10 values,11 bracket squiggly,11 void,10.6
bracketoperator,8.1,10.2,12.1
methodappend,10.15
branch,5.5,5.13
methodresolutionorder,18.9
breakstatement,7.4
en.wikibooks.org/wiki/Think_Python/Print_version
methodsyntax,17.2
239/282
10/24/13
bug,1.3,1.3,1.7
method,bound,19.6
worst,17.12
method,list,10.6
worstever,19.11
minfunction,12.3,12.4
model,mental,A.3.1
Callableobject,19.7
modifier,16.3,16.6
Canvascoordinate,19.3,19.8
module,3.3,3.14,3.14
Canvasitem,19.3
anydbm,14.6
Canvasobject,15.9
bisect,10.15
Canvaswidget,19.3
copy,15.6
CarTalk,9.7,9.7,9.7,11.10,12.11
datetime,16.7
Cardclass,18.1
Gui,19.1
en.wikibooks.org/wiki/Think_Python/Print_version
240/282
10/24/13
Collatzconjecture,7.3
HTMLParser,19.11
CzechRepublic,nationalflag,15.9
Image,19.11
calculator,1.8,2.12
os,14.4
callgraph,11.5,11.9
pickle,14.1,14.7
callback,19.2,19.6,19.7,19.8,19.9,19.10
pprint,11.8
card,playing,18
profile,13.9
carrying,additionwith,7.6,16.2,16.4
random,10.15,12.7,13.2,18.6
casesensitivity,variablenames,2.10
reload,14.9,A.1.1
catch,14.11
shelve,14.7,14.12
chainedconditional,5.6,5.13
string,13.1
character,8.1
structshape,12.9
checksum,14.12
en.wikibooks.org/wiki/Think_Python/Print_version
urllib,14.12,19.11
241/282
10/24/13
childclass,18.7,18.10
Visual,17.12
choicefunction,13.2
vpython,17.12
circlefunction,4.3
World,15.9
circulardefinition,6.5 moduleobject,3.3,14.9 class,15.1,15.8 module,writing,14.9 Card,18.1 modulusoperator,5.1,5.13 Date,16.7 mromethod,18.9 Deck,18.4 multilinestring,4.9,A.1 Hand,18.7 multipleassignment,7.1,7.8,11.6 Kangaroo,17.12 multiplicity(inclassdiagram),18.8,18.10 Point,15.1,17.5 mutability,8.5,10.2,10.5,10.11,11.6,12.1,12.8,15.5
en.wikibooks.org/wiki/Think_Python/Print_version 242/282
10/24/13
SimpleTurtleWorld,19.6
NameError,3.9,A.2.3
Time,16.1
Newtonsmethod,7.5
Nonespecialvalue,3.11,6.1,6.10,10.6,10.8 classattribute,18.2,18.10 naturallanguage,1.4,1.7 classdefinition,15.1 negativeindex,8.2 classdiagram,18.8,18.10 nestedconditional,5.7,5.13 classobject,15.1,15.8 nestedlist,10.1,10.3,10.14 closemethod,14.2,14.6,14.8 newline,5.11,7.1,18.5 cmpfunction,18.3 notoperator,5.3 __cmp__method,18.3
en.wikibooks.org/wiki/Think_Python/Print_version
243/282
10/24/13
colon,3.5,A.1
number,random,13.2
colorlist,15.9,17.12 OverflowError,5.12 comment,2.9,2.11 object,8.5,8.12,10.10,10.10,10.14,15.1 commutativity,2.8,17.8 Callable,19.7 comparefunction,6.1 Canvas,15.9 comparison string,8.10 class,15.1
tuple,12.7,18.3
copying,15.6
10/24/13
printing,17.2 concatenation,2.8,2.11,3.9,8.3,8.5,10.9
list,10.4,10.12,10.15
objectcode,1.1,1.7
objectdiagram,15.2,15.3,15.6,15.8,16.1,18.2 condition,5.4,5.13,7.3,A.2.2 objectorientedlanguage,17.11 conditional,A.1 objectorientedprogramming,17.1,17.11,18.7 chained,5.6,5.13 octal,2.2 nested,5.7,5.13 odometer,9.7 conditionalexecution,5.4 openfunction,9.1,9.1,14.2,14.5,14.6 conditionaloperator,18.3 operand,2.5,2.11
en.wikibooks.org/wiki/Think_Python/Print_version
245/282
10/24/13
conditionalstatement,5.4,5.13,6.4
operator,2.11
configmethod,19.3
and,5.3
consistencycheck,11.8,16.4
bitwise,2.5
contributors,0
boolean,8.9
conversion type,3.2
bracket,8.1,10.2,12.1
comparison,5.2
coordinate Canvas,19.3,19.8
conditional,18.3
coordinatesequence,19.4
in,8.9,9.3,10.2,11
copy deep,15.6
is,10.10,15.6
logical,5.2,5.3
en.wikibooks.org/wiki/Think_Python/Print_version 246/282
10/24/13
copymodule,15.6
overloading,17.11
copyingobjects,15.6
slice,8.4,8.13,10.5,10.12,12.1
countmethod,8.8
string,2.8
counter,8.7,8.12,11.1,11.6
update,10.7
10/24/13
optionalparameter,13.5,17.5 Dateclass,16.7 oroperator,5.3 Deckclass,18.4 orderofoperations,2.7,2.10,A.3.2 Dijkstra,Edsger,9.5 osmodule,14.4 Doyle,ArthurConan,1.3.4 other(parametername),17.4 DSUpattern,12.7,12.10,13.4 overloading,17.11 datastructure,12.9,12.10,13.9 override,13.5,13.11,17.5,18.3,18.7,18.9 database,14.6,14.11,14.12
datetimemodule,16.7
PEMDAS,2.7
deadcode,6.1,6.10,A.2.4
PIL(PythonImagingLibrary),19.11
debugger(pdb),A.2.3
Pointclass,15.1,17.5
en.wikibooks.org/wiki/Think_Python/Print_version
248/282
10/24/13
debugging,1.3,1.3,1.6,1.7,2.10,3.13,4.10,5.12,6.9,8.11,9.5,10.13,11.8, 12.9,13.10,14.10,15.7,16.5,17.10,18.9,19.9,A
ProjectGutenberg,13.1
Puzzler,9.7,9.7,9.7,11.10,12.11 bybisection,7.7 Pythagoreantheorem,6.2 emotionalresponse,1.6,A.3.4 Python3.0,1.5,2.5,5.11,11.7,12.5 experimental,1.3.4 Pythondebugger(pdb),A.2.3 superstition,A.3.4 PythonImagingLibrary(PIL),19.11 deck,playingcards,18.4 packingwidgets,19.6,19.10 declaration,11.6,11.9 palindrome,6.11,8.13,9.4,9.7,9.7 decoratesortundecoratepattern,12.7 parameter,3.8,3.9,3.14,10.12 decrement,7.2,7.8
gather,12.4
deepcopy,15.6,15.8
optional,13.5,17.5
deepcopyfunction,15.6
en.wikibooks.org/wiki/Think_Python/Print_version
other,17.4
249/282
10/24/13
defkeyword,3.5
self,17.2
class,15.1
matching,1.3.1
function,3.5
overridingprecedence,2.7
recursive,12.11
parametersin,3.8,3.9
delimiter,10.9,10.14
en.wikibooks.org/wiki/Think_Python/Print_version
parse,1.4,1.7,14.12
250/282
10/24/13
deterministic,13.2,13.11
passstatement,5.4
developmentplan,4.11
path,14.4,14.11
encapsulationandgeneralization,4.8
absolute,14.4
incremental,6.2,A.1
relative,14.4
prototypeandpatch,16.2,16.4
decoratesortundecorate,12.7
randomwalkprogramming,13.10,A.3.4
filter,10.7,10.14
class,18.8,18.10
reduce,10.7,10.14
en.wikibooks.org/wiki/Think_Python/Print_version
251/282
10/24/13
object,15.2,15.3,15.6,15.8,16.1,18.2
search,8.6,8.12,9.3,11.3
stack,3.10,10.12
swap,12.2
state,2.2,7.1,8.11,10.2,10.10,10.11,11.4,12.6,15.2,15.3,15.6,16.1,18.2 pdb(Pythondebugger),A.2.3
__dict__attribute,17.10
permission,file,14.5
dictfunction,11
persistence,14.1,14.11
dictionary,11,11,11.9,12.6,A.2.3
pi,3.3,7.9
initialize,12.6
picklemodule,14.1,14.7
invert,11.4
pickling,14.7
lookup,11.3
pie,4.12
loopingwith,11.2
pipe,14.8,14.12
reverselookup,11.3
pixelcoordinate,19.8
en.wikibooks.org/wiki/Think_Python/Print_version
252/282
10/24/13
subtraction,13.6
plaintext,9.1,13.1,14.12,19.11
traversal,12.6,17.10
planneddevelopment,16.4,16.6
dispatch typebased,17.9
popmethod,10.8,18.6
10/24/13
division floatingpoint,2.5
pprintmodule,11.8
divmod,12.3,16.4
prefix,13.8
docstring,4.9,4.11,15.1
prettyprint,11.8
documentation,1.8
printstatement,1.5,1.7,17.6,A.2.4
dotnotation,3.3,3.14,8.8,15.2,17.2,18.2
problemrecognition,9.3,9.4,9.6
doubleletters,9.7
problemsolving,1,1.7
draganddrop,19.8
profilemodule,13.9
duplicate,10.15,10.15,11.10,14.12
program,1.2,1.7
programtesting,9.5 Einstein,Albert,4.6
en.wikibooks.org/wiki/Think_Python/Print_version 254/282
10/24/13
programminglanguage,1.1 Entrywidget,19.5 prompt,1.1,1.7,5.11 Euclidsalgorithm,6.11 prose,1.4 Eventobject,19.8 prototypeandpatch,16.2,16.4,16.6 element,10.1,10.14 pseudorandom,13.2,13.11 elementdeletion,10.8 purefunction,16.2,16.6 elifkeyword,5.6 python.org,1.8 ellipses,3.5
elsekeyword,5.5
quotationmark,1.5,2.1,2.1,4.9,8.4,A.1
emailaddress,12.2
embeddedobject,15.3,15.8,17.12
Ramanujan,Srinivasa,7.9
copying,15.6
Rectangleclass,15.3
en.wikibooks.org/wiki/Think_Python/Print_version
255/282
10/24/13
RSAalgorithm,11.7 emotionaldebugging,1.6,A.3.4 RuntimeError,5.10,6.8 emptylist,10.1 raddmethod,17.8 emptystring,8.12,10.9 radian,3.3 encapsulation,4.4,4.11,6.3,7.5,8.7,18.7 rage,A.3.4 encode,18.1,18.10 raisestatement,11.3,16.5 encrypt,18.1 randintfunction,10.15,13.2 encryption,11.7 randomfunction,12.7,13.2 endoflinecharacter,14.10 randommodule,10.15,12.7,13.2,18.6 enumeratefunction,12.5 randomnumber,13.2 epsilon,7.5 randomtext,13.8 equalityandassignment,7.1 randomwalkprogramming,13.10,A.3.4
en.wikibooks.org/wiki/Think_Python/Print_version 256/282
10/24/13
runtime,1.3.2,2.10,5.10,5.12,A
readlinemethod,9.1,14.8
semantic,1.3.3,2.1,2.10,8.11,A,A.3
recursion,5.8,5.8,5.13,6.5,6.6
shape,12.9
basecase,5.9
syntax,1.3.1,2.10,A
infinite,5.10,6.8,A.2.2
errorchecking,6.8
recursivedefinition,6.5,12.11
errormessage,1.3.1,1.3.3,1.6,2.1,2.10,A.1
reducepattern,10.7,10.14
evalfunction,7.9
reducibleword,11.10,12.11
evaluate,2.6
en.wikibooks.org/wiki/Think_Python/Print_version
redundancy,1.4
257/282
10/24/13
event,19.10
refactoring,4.7,4.7
eventhandler,19.8
reference,10.11,10.12,10.14
eventloop,19.1,19.10
aliasing,10.11
eventstring,19.8 relativepath,14.4,14.11 eventdrivenprogramming,19.2,19.9,19.10 reloadfunction,14.9,A.1.1 exception,1.3.2,1.7,2.10,A,A.2.3 removemethod,10.8 AttributeError,15.7,A.2.3 repetition,4.2 IndexError,8.2,8.11,10.2,A.2.3 list,10.4 IOError,14.5
KeyError,11,A.2.3
replacemethod,13.1
NameError,3.9,A.2.3
reprfunction,14.10
en.wikibooks.org/wiki/Think_Python/Print_version
258/282
10/24/13
OverflowError,5.12
representation,15.1,15.3,18.1
RuntimeError,5.10
returnstatement,5.8,6.1,A.3.3
SyntaxError,3.4
returnvalue,3.1,3.14,6.1,15.4
TypeError,8.1,8.5,11.4,12.1,12.4,14.3,17.3,A.2.3
tuple,12.3
exception,catching,14.5
reversedfunction,12.8
executable,1.1,1.7
rotation letters,11.10
exercise,secret,14.12
existsfunction,14.4
rotation,letter,8.13
experimentaldebugging,1.3.4,13.10
rulesofprecedence,2.7,2.11
en.wikibooks.org/wiki/Think_Python/Print_version
259/282
10/24/13
expression,2.5,2.6,2.11
runningpace,1.8,2.12,16.7
bigandhairy,A.3.2
runtimeerror,1.3.2,2.10,5.10,5.12,A,A.2.3
boolean,5.2,5.13
SVG,19.11 Falsespecialvalue,5.2 Swampy,4.1,9.1,15.9,18.11,19.1 FermatsLastTheorem,5.14 SyntaxError,3.4 Framewidget,19.6 safelanguage,1.3.2 FreeDocumentationLicense,GNU,0,0 sanitycheck,11.8 factorialfunction,6.5,6.8 scaffolding,6.2,6.10,11.8 fibonaccifunction,6.7,11.5 scatter,12.4,12.10 file,14
en.wikibooks.org/wiki/Think_Python/Print_version 260/282
10/24/13
compression,14.8
script,1.1,1.7
permission,14.5
scriptmode,1.1,1.7,2.4,3.11
readingandwriting,14.2
search,11.3
searchpattern,8.6,8.12,9.3 fileobject,9.1,9.6 search,bisection,10.15 filename,14.4 secretexercise,14.12 filterpattern,10.7,10.14 self(parametername),17.2 findfunction,8.6 semanticerror,1.3.3,1.7,2.1,2.10,8.11,A,A.3 flag,11.6,11.9 semantics,1.3.3,1.7,17.1 floatfunction,3.2 sequence,8.1,8.12,10.1,10.9,12.1,12.8 floattype,2.1 coordinate,19.4 floatingpoint,2.11,7.5
en.wikibooks.org/wiki/Think_Python/Print_version 261/282
10/24/13
floatingpointdivision,2.5
set,13.6
floordivision,2.5,2.11,5.12
anagram,12.11,14.7
flowofexecution,3.7,3.14,6.7,6.9,7.3,18.9,19.9,A.2.2 setmembership,11 flower,4.12 setdefaultmethod,11.4 folder,14.4 sexagesimal,16.4 forloop,4.2,8.3,10.3,12.5 shallowcopy,15.6,15.8 formallanguage,1.4,1.7 shape,12.10 formatoperator,14.3,14.11,A.2.3 shapeerror,12.9 formatsequence,14.3,14.11 shell,14.8 formatstring,14.3,14.11 shelvemodule,14.7,14.12 frabjuous,6.5 shufflefunction,18.6
en.wikibooks.org/wiki/Think_Python/Print_version 262/282
10/24/13
fruitfulfunction,3.11,3.14
list,10.5
frustration,A.3.4
string,8.4
function,3.5,3.14,17.1
tuple,12.1
abs,6.1
update,10.5
10/24/13
dict,11
None,3.11,6.1,6.10,10.6,10.8
enumerate,12.5
True,5.2
eval,7.9 splitmethod,10.9,12.2 exists,14.4 sqrt,6.2 factorial,6.5 sqrtfunction,3.3 fibonacci,6.7,11.5 squareroot,7.5 find,8.6 squigglybracket,11 float,3.2
en.wikibooks.org/wiki/Think_Python/Print_version 264/282
10/24/13
getattr,17.10
stackdiagram,3.10,3.10,3.14,4.12,5.9,6.5,6.11, 10.12
getcwd,14.4
statediagram,2.2,2.11,7.1,8.11,10.2,10.10,10.11, 11.4,12.6,15.2,15.3,15.6,16.1,18.2
hasattr,15.7,17.10
statement,2.4,2.11
int,3.2
assert,16.5
isinstance,6.8,17.8
assignment,2.2,7.1
len,3.15,8.2,11
break,7.4
list,10.9
compound,5.4
log,3.3
conditional,5.4,5.13,6.4
max,12.3,12.4
for,4.2,8.3,10.3
min,12.3,12.4
global,11.6
open,9.1,9.1,14.2,14.5,14.6
if,5.4
en.wikibooks.org/wiki/Think_Python/Print_version
265/282
10/24/13
polygon,4.3
import,3.14,4.1,14.9
popen,14.8
pass,5.4
randint,10.15,13.2
print,1.5,1.7,17.6,A.2.4
random,12.7,13.2
raise,11.3,16.5
raw_input,5.11
return,5.8,6.1,A.3.3
recursive,5.8
try,14.5
reload,14.9,A.1.1
while,7.3
10/24/13
accumulator,18.5 str,3.2 comparison,8.10 sum,12.4 empty,10.9 tuple,12.1 immutable,8.5 type,15.7 method,8.8 zip,12.5 multiline,4.9,A.1
functionargument,3.8
operation,2.8
functioncall,3.1,3.14
slice,8.4
functioncomposition,6.3
triplequoted,4.9
10/24/13
pure,16.2
structure,1.4
function,trigonometric,3.3
withborrowing,7.6
10/24/13
functionalprogrammingstyle,16.3,16.6 suit,18.1
GCD(greatestcommondivisor),6.11
sumfunction,12.4
GNUFreeDocumentationLicense,0,0
superclass,18.7
GUI,19.1,19.10
superstitiousdebugging,A.3.4
Guimodule,19.1
swappattern,12.2
gammafunction,6.8
syntax,1.3.1,1.3.1,1.7,17.1,A.1
gather,12.4,12.10
syntaxerror,1.3.1,1.7,2.10,A
10/24/13
graphicaluserinterface,19.1
TurtleWorld,4.1,5.14,18.11
greatestcommondivisor(GCD),6.11
TypeError,8.1,8.5,11.4,12.1,12.4,14.3,17.3,A.2.3
grid,3.15
temporaryvariable,6.1,6.10,A.3.2
guardianpattern,6.8,6.10,8.11
testcase,minimal,A.2.4
gzip(Unixcommand),14.8
testing andabsenceofbugs,9.5
HASArelationship,18.8,18.10
incrementaldevelopment,6.2
en.wikibooks.org/wiki/Think_Python/Print_version
270/282
10/24/13
Handclass,18.7
interactivemode,1.1
Hello,World,1.5
ishard,9.5
Holmes,Sherlock,1.3.4
knowingtheanswer,6.2
HTMLParsermodule,19.11
leapoffaith,6.6
hanging,A.2.2
minimaltestcase,A.2.4
hashable,11.4,11.9,12.6
random,13.8
10/24/13
histogram,11.1,11.1,11.9
randomchoice,13.2,13.7
dictionary,17.10
wordfrequencies,13.3
list,10.3
homophone,11.10
traverse dictionary,12.6
hyperlink,19.11 triangle,5.14
hypotenuse,6.2
trigonometricfunction,3.3
IMDb(InternetMovieDatabase),14.12
triplequotedstring,4.9
Imagemodule,19.11
trystatement,14.5
IndexError,8.2,8.11,10.2,A.2.3
tuple,12.1,12.3,12.8,12.10
en.wikibooks.org/wiki/Think_Python/Print_version
272/282
10/24/13
InternetMovieDatabase(IMDb),14.12
askeyindictionary,12.6,13.9
IOError,14.5
assignment,12.2
ISArelationship,18.8,18.10
comparison,12.7,18.3
identical,10.14
inbrackets,12.6
identity,10.10
singleton,12.1
ifstatement,5.4
slice,12.1
imageviewer,19.11 tupleassignment,12.3,12.5,12.10 immutability,8.5,8.5,8.12,10.11,11.4,12.1,12.8 tuplefunction,12.1 implementation,11.1,11.9,13.9 turtletypewriter,4.12 importstatement,3.14,4.1,14.9 type,2.1,2.1,2.11 inoperator,8.9,9.3,10.2,11 bool,5.2 increment,7.2,7.8,16.3,17.3
en.wikibooks.org/wiki/Think_Python/Print_version 273/282
10/24/13
dict,11 incrementaldevelopment,6.10,A.1 file,14 indentation,3.5,17.2,A.1 float,2.1 index,8.1,8.1,8.11,8.12,10.2,10.14,11,A.2.3 int,2.1 loopingwith,9.4,10.3 list,10 negative,8.2 long,11.7 slice,8.4,10.5 set,13.6 startingatzero,8.1,10.2 str,2.1
infiniteloop,7.3,7.8,19.1,A.2.2,A.2.2
tuple,12.1
infiniterecursion,5.10,5.13,6.8,A.2.2,A.2.2
userdefined,15.1,16.1
10/24/13
instanceattribute,15.2,15.8,18.2,18.10
instantiation,15.1
UML,18.8
intfunction,3.2
UnboundLocalError,11.6
inttype,2.1
Unixcommand gzip,14.8
URL,14.12,19.11
en.wikibooks.org/wiki/Think_Python/Print_version
275/282
10/24/13
interactivemode,1.1,1.7,2.4,3.11
underscorecharacter,2.3
interface,4.6,4.10,4.11,18.9
uniqueness,10.15
interlockingwords,10.15
update,7.2,7.5,7.8
interpret,1.1,1.7
coordinate,19.8
invariant,16.5,16.6,19.9
database,14.6
invertdictionary,11.4
globalvariable,11.6
invocation,8.8,8.12
histogram,13.3
isoperator,10.10,15.6
item,10.3
isinstancefunction,6.8,17.8
slice,10.5
10/24/13
urllibmodule,14.12,19.11
itemassignment,8.5,10.2,12.1
usebeforedef,2.10,3.6
itemupdate,10.3
userdefinedtype,15.1,16.1
itemsmethod,12.6 ValueError,5.11,11.3,12.2
iteration,7,7.3,7.8
Visualmodule,17.12
joinmethod,10.9,18.5
value,2.1,2.11,10.10,10.10,11.9
10/24/13
keyword,2.3,2.3,2.11,A.1
variablelengthargumenttuple,12.4
def,3.5
vectorgraphics,19.11
elif,5.6
veneer,18.6,18.10
else,5.5
voidfunction,3.11,3.14
10/24/13
highlevel,1.1
whitespace,3.13,5.12,9.1,14.10,A.1
lowlevel,1.1
widget,19.1,19.10
natural,1.4
Button,19.2
programming,1.1
Canvas,19.3
safe,1.3.2
Entry,19.5
Turingcomplete,6.5
Frame,19.6
en.wikibooks.org/wiki/Think_Python/Print_version
279/282
10/24/13
letterrotation,8.13,11.10
widget,packing,19.6
lipogram,9.2
wordcount,14.9
list,10,10.9,10.14,12.8
wordfrequency,13.1,13.12
asargument,10.12
word,reducible,11.10,12.11
comprehension,10.7
workingdirectory,14.4
concatenation,10.4,10.12,10.15
worstbug,17.12
copy,10.5
ever,19.11
element,10.2
empty,10.1
Zipfslaw,13.12
function,10.9
zero,indexstartingat,8.1,10.2
index,10.2
zipfunction,12.5
membership,10.2
en.wikibooks.org/wiki/Think_Python/Print_version
usewithdict,12.6
280/282
10/24/13
method,10.6
nested,10.1,10.3
ofobjects,18.4
oftuples,12.5
operation,10.4
repetition,10.4
slice,10.5
traversal,10.3,10.14
<IMGSRC="previous_motif.gif"ALT="Previous"><IMGSRC="contents_motif.gif"ALT="Up"> Retrievedfrom"http://en.wikibooks.org/w/index.php?title=Think_Python/Print_version&oldid=1931999"
Thispagewaslastmodifiedon23October2013,at21:16. TextisavailableundertheCreativeCommonsAttribution/ShareAlikeLicenseadditionaltermsmayapply.Byusingthissite,youagreetotheTermsof UseandPrivacyPolicy.
en.wikibooks.org/wiki/Think_Python/Print_version 281/282
10/24/13
en.wikibooks.org/wiki/Think_Python/Print_version
282/282