[Go to site: main page, start]

100% found this document useful (3 votes)
233 views282 pages

Think Python: A Programming Guide

This document summarizes the preface of the book "Think Python" by Allen B. Downey. It discusses the origins and development of the book, which started as a Java textbook but was translated to Python. The author's goals were to keep it short, use careful vocabulary, and build concepts gradually. It was released under an open license. Over the years, the author has continued improving the book based on feedback, adding exercises and case studies. Many contributors have helped by submitting corrections and suggestions.

Uploaded by

Nimisha Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
233 views282 pages

Think Python: A Programming Guide

This document summarizes the preface of the book "Think Python" by Allen B. Downey. It discusses the origins and development of the book, which started as a Java textbook but was translated to Python. The author's goals were to keep it short, use careful vocabulary, and build concepts gradually. It was released under an open license. Over the years, the author has continued improving the book based on feedback, adding exercises and case studies. Many contributors have helped by submitting corrections and suggestions.

Uploaded by

Nimisha Singh
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

ThinkPython/Printversion Preface
Chapter0:Preface
Thestrangehistoryofthisbook
([Link][1]) InJanuary1999,[Link] intheclasswastoohighand,evenforstudentswhosucceeded,theoveralllevelofachievementwastoolow. [Link],withtoomuchunnecessarydetailaboutJava,andnotenoughhighlevelguidanceabouthowto [Link]"trapdooreffect":theywouldstartouteasy,proceedgradually,andthensomewherearoundChapter5thebottom [Link],toofast,andIwouldspendtherestofthesemesterpickingupthepieces. Twoweeksbeforethefirstdayofclass,Idecidedtowritemyownbook. Mygoalswere: Keepitshort.Itisbetterforstudentstoread10pagesthanread50pages. [Link]. [Link],Itookthemostdifficulttopicsandsplitthemintoaseriesofsmallsteps. Focusonprogramming,[Link]. Ineededatitle,soonawhimIchose HowtoThinkLikeaComputerScientist . Myfirstversionwasrough,[Link],andtheyunderstoodenoughthatIcouldspendclasstimeonthehardtopics,the interestingtopicsand(mostimportant)lettingthestudentspractice. IreleasedthebookundertheGNUFreeDocumentationLicense,whichallowsuserstocopy,modify,anddistributethebook. [Link],ahighschoolteacherinVirginia,[Link] translation,andIhadtheunusualexperienceoflearningPythonbyreadingmyownbook. JeffandIrevisedthebook,incorporatedacasestudybyChrisMeyers,andin2001wereleased HowtoThinkLikeaComputerScientist:Learningwith Python,[Link],[Link] [Link]([Link] In2003,[Link],learned more,workedonmoreinterestingprojects,andgenerallyhadalotmorefun. OverthelastfiveyearsIhavecontinuedtodevelopthebook,correctingerrors,improvingsomeoftheexamplesandaddingmaterial,[Link]

[Link]/wiki/Think_Python/Print_version

1/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

OverthelastfiveyearsIhavecontinuedtodevelopthebook,correctingerrors,improvingsomeoftheexamplesandaddingmaterial,[Link] 2008Istartedworkonamajorrevisionatthesametime,IwascontactedbyaneditoratCambridgeUniversityPresswhowasinterestedinpublishingthe [Link]! Theresultisthisbook,nowwiththelessgrandiosetitle [Link]: [Link],andwarnings aboutPythonpitfalls. [Link],butIthoughttheywereincongruent withtherestofthebook. Iaddedmoreexercises,rangingfromshorttestsofunderstandingtoafewsubstantialprojects. Iaddedaseriesofcasestudieslongerexampleswithexercises,solutions,[Link],asuiteofPython [Link],codeexamples,[Link] ([Link] Iexpandedthediscussionofprogrammingdevelopmentplansandbasicdesignpatterns. [Link],notPython,butnowIthinkthebookgetsmoreleveragefromthelanguage. Ihopeyouenjoyworkingwiththisbook,andthatithelpsyoulearntoprogramandthink,atleastalittlebit,likeacomputerscientist. [Link] NeedhamMA [Link].

Acknowledgements
Firstandmostimportantly,IthankJeffElkner,whotranslatedmyJavabookintoPython,whichgotthisprojectstartedandintroducedmetowhathasturned outtobemyfavoritelanguage. IalsothankChrisMeyers,whocontributedseveralsectionsto HowtoThinkLikeaComputerScientist . AndIthanktheFreeSoftwareFoundationfordevelopingtheGNUFreeDocumentationLicense,whichhelpedmakemycollaborationwithJeffandChris possible. IalsothanktheeditorsatLuluwhoworkedon HowtoThinkLikeaComputerScientist . Ithankallthestudentswhoworkedwithearlierversionsofthisbookandallthecontributors(listedbelow)whosentincorrectionsandsuggestions. AndIthankmywife,Lisa,forherworkonthisbook,andGreenTeaPress,andeverythingelse,too.

ContributorList

[Link]/wiki/Think_Python/Print_version

[Link],andenthusiasmfor

2/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],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,[Link],too,butnotquiteas [Link]! LloydHughAllensentinacorrectiontoSection8.4. YvonBouliannesentinacorrectionofasemanticerrorinChapter5. FredBremmersubmittedacorrectioninSection2.1. JonahCohenwrotethePerlscriptstoconverttheLaTeXsourceforthisbookintobeautifulHTML. MichaelConlonsentinagrammarcorrectioninChapter2andanimprovementinstyleinChapter1,andheinitiateddiscussiononthetechnical aspectsofinterpreters. BenoitGirardsentinacorrectiontoahumorousmistakeinSection5.6. CourtneyGleasonandKatherineSmithwrote h o r s e b e t . p y ,[Link] foundonthewebsite. LeeHarrsubmittedmorecorrectionsthanwehaveroomtolisthere,andindeedheshouldbelistedasoneoftheprincipaleditorsofthetext. [Link]. DavidKershawfixedthebroken c a t T w i c e functioninSection3.10. EddieLamhassentinnumerouscorrectionstoChapters1,2,[Link] helpedussetupaversioningscheme. ManYongLeesentinacorrectiontotheexamplecodeinSection2.4. DavidMayopointedoutthattheword"unconsciously"inChapter1neededtobechangedto"subconsciously". ChrisMcAloonsentinseveralcorrectionstoSections3.9and3.10. [Link]. [Link] 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. [Link].
[Link]/wiki/Think_Python/Print_version 3/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],and theyhavemadenumerouscorrectionsandsuggestions. KeithVerheydensentinacorrectioninChapter3. PeterWinstanleyletusknowaboutalongstandingerrorinourLatininChapter3. ChrisWrobelmadecorrectionstothecodeinthechapteronfileI/Oandexceptions. [Link],he providedcontinualguidanceintheearlystagesofthebook. ChristophZwerschkesentseveralcorrectionsandpedagogicsuggestions,andexplainedthedifferencebetween gleichand selbe. JamesMayersentusawholeslewofspellingandtypographicalerrors,includingtwointhecontributorlist. HaydenMcAfeecaughtapotentiallyconfusinginconsistencybetweentwoexamples. [Link] version. TauhidulHoqueandLexBerezhnycreatedtheillustrationsinChapter1andimprovedmanyoftheotherillustrations. Dr.MicheleAlzettacaughtanerrorinChapter8andsentsomeinterestingpedagogiccommentsandsuggestionsaboutFibonacciandOldMaid. AndyMitchellcaughtatypoinChapter1andabrokenexampleinChapter2. KalinHarveysuggestedaclarificationinChapter7andcaughtsometypos. ChristopherP.SmithcaughtseveraltyposandishelpinguspreparetoupdatethebookforPython2.2. DavidHutchinscaughtatypointheForeword. GregorLinglisteachingPythonatahighschoolinVienna,[Link],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.
[Link]/wiki/Think_Python/Print_version 4/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

AbelDavidandAlexisDinnoremindedusthatthepluralofmatrixismatrices,[Link],buttworeaders [Link]. CharlesThayerencouragedustogetridofthesemicolonswehadputattheendsofsomestatementsandtocleanupouruseofargumentand parameter. RogerSperbergpointedoutatwistedpieceoflogicinChapter3. SamBullpointedoutaconfusingparagraphinChapter2. AndrewCheungpointedouttwoinstancesofusebeforedef. C.CoreyCapelspottedthemissingwordintheThirdTheoremofDebuggingandatypoinChapter4. AlessandrahelpedclearupsomeTurtleconfusion. WimChampagnefoundabrainoinadictionaryexample. DouglasWrightpointedoutaproblemwithfloordivisionin a r c . JaredSpindorfoundsomejetsamattheendofasentence. LinPeihengsentanumberofveryhelpfulsuggestions. RayHagtvedtsentintwoerrorsandanotquiteerror. TorstenHbschpointedoutaninconsistencyinSwampy. IngaPetuhhovcorrectedanexampleinChapter14. ArneBabenhauserheidesentseveralhelpfulcorrections. [Link]. [Link]. GordonShephardsentinseveralcorrections,allinseparateemails. AndrewTurner s p o t tedanerrorinChapter8. AdamHobartfixedaproblemwithfloordivisionin a r c . DarylHammondandSarahZimmermanpointedoutthatIservedup m a t h . p i [Link]. GeorgeSassfoundabuginaDebuggingsection. BrianBinghamsuggestedExercise11.9. LeahEngelbertFentonpointedoutthatIused t u p l e asavariablename,[Link] def. JoeFunkespottedatypo. ChaochaoChenfoundaninconsistencyintheFibonacciexample. JeffPaineknowsthedifferencebetweenspaceandspam. LubosPintessentinatypo. GreggLindandAbigailHeithoffsuggestedExercise14.6. [Link] ConcreteAbstractions,whichyoumightwant toreadwhenyouaredonewiththisbook. ChotipatPornavalaifoundanerrorinanerrormessage.
[Link]/wiki/Think_Python/Print_version 5/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

StanislawAntolsentalistofveryhelpfulsuggestions. EricPashmansentanumberofcorrectionsforChapters411. MiguelAzevedofoundsometypos. JianhuaLiusentinalonglistofcorrections. NickKingfoundamissingword. MartinZuthersentalonglistofsuggestions. AdamZimmermanfoundaninconsistencyinmyinstanceofaninstanceandseveralothererrors. RatnakarTiwarisuggestedafootnoteexplainingdegeneratetriangles. AnuragGoelsuggestedanothersolutionfor i s _ a b e c e d a r i a n [Link]. KelliKratzerspottedoneoftheytypos. MarkGriffithspointedoutaconfusingexampleinChapter3. RoydanOngiefoundanerrorinmyNewtonsmethod.

Thefurtherstrangeadventuresofthisbook
InSeptemberof2008,WhiteknightconvertedtheHTMLversionof"ThinkPython"atGreenTeaPress[2]toaWikitextversionatWikibooks[3].Nowanyone canimprovethetext. 1. "Thestrangehistoryofthisbook"([Link] 2. "ThinkPython"atGreenTeaPress([Link] 3. Wikibooks:ThinkPython([Link]

Thewayoftheprogram
[Link],engineering, [Link],computerscientistsuseformallanguagestodenoteideas(specificallycomputations).Likeengineers,theydesign things,[Link],theyobservethebehaviorofcomplexsystems,form hypotheses,andtestpredictions. Thesinglemostimportantskillforacomputerscientistis [Link],thinkcreativelyabout solutions,[Link],theprocessoflearningtoprogramisanexcellentopportunitytopracticeproblem [Link],Thewayoftheprogram. Ononelevel,youwillbelearningtoprogram,[Link],[Link],that endwillbecomeclearer.

ThePythonprogramminglanguage
[Link] highlevellanguageotherhighlevellanguagesyoumighthaveheardofare C,C++,Perl,andJava.
[Link]/wiki/Think_Python/Print_version 6/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Therearealso lowlevellanguages,[Link],computerscanonlyexecute [Link] sometime,whichisasmalldisadvantageofhighlevellanguages. [Link],[Link], theyareshorterandeasiertoread,[Link],highlevellanguagesare portable,meaningthattheycanrunondifferent [Link]. Duetotheseadvantages,[Link]. Twokindsofprogramsprocesshighlevellanguagesintolowlevellanguages: interpretersand [Link] executesit,[Link],alternatelyreadinglinesandperformingcomputations.

[Link],thehighlevelprogramiscalledthe sourcecode, andthetranslatedprogramiscalledthe objectcodeorthe [Link],youcanexecuteitrepeatedlywithoutfurther translation.

[Link]: interactive modeand [Link],youtypePythonprogramsandtheinterpreterprintstheresult:


> > >1+1 2

Thechevron, > > > ,isthe [Link] 1+1 ,theinterpreterreplies 2 . Alternatively,youcanstorecodeinafileandusetheinterpretertoexecutethecontentsofthefile,whichiscalleda [Link],Pythonscripts havenamesthatendwith . p y .
[Link]/wiki/Think_Python/Print_version 7/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Toexecutethescript,[Link],youwouldtype p y t h o nd i n s d a l e . p y .Inotherdevelopment environments,[Link] p y t h o n . o r g . [Link] fewlines,youshouldsaveyourcodeasascriptsoyoucanmodifyandexecuteitinthefuture.

Whatisaprogram?
A [Link],suchassolvinga systemofequationsorfindingtherootsofapolynomial,butitcanalsobeasymboliccomputation,suchassearchingandreplacingtextinadocumentor (strangelyenough)compilingaprogram. Thedetailslookdifferentindifferentlanguages,butafewbasicinstructionsappearinjustabouteverylanguage: input: Getdatafromthekeyboard,afile,orsomeotherdevice. output: Displaydataonthescreenorsenddatatoafileorotherdevice. math: Performbasicmathematicaloperationslikeadditionandmultiplication. conditionalexecution: Checkforcertainconditionsandexecutetheappropriatesequenceofstatements. repetition: Performsomeactionrepeatedly,usuallywithsomevariation. Believeitornot,[Link],nomatterhowcomplicated,ismadeupofinstructionsthatlookpretty [Link],complextaskintosmallerandsmallersubtasksuntilthesubtasksare simpleenoughtobeperformedwithoneofthesebasicinstructions. Thatmaybealittlevague,butwewillcomebacktothistopicwhenwetalkabout algorithms.

Whatisdebugging?
[Link],programmingerrorsarecalled bugsandtheprocessoftrackingthemdowniscalled debugging. Threekindsoferrorscanoccurinaprogram:syntaxerrors,runtimeerrors,[Link] downmorequickly. Syntaxerrors Pythoncanonlyexecuteaprogramifthesyntaxiscorrectotherwise,theinterpreterdisplaysanerrormessage. Syntaxreferstothestructureofaprogram [Link],parentheseshavetocomeinmatchingpairs,so ( 1+2 ) islegal,but 8 ) isa syntaxerror.
[Link]/wiki/Think_Python/Print_version 8/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

InEnglishreaderscantoleratemostsyntaxerrors,[Link] [Link],Pythonwilldisplayanerrormessageandquit,andyouwillnotbeabletorunyour [Link],[Link],you willmakefewererrorsandfindthemfaster. Runtimeerrors Thesecondtypeoferrorisaruntimeerror,[Link] called exceptionsbecausetheyusuallyindicatethatsomethingexceptional(andbad)hashappened. Runtimeerrorsarerareinthesimpleprogramsyouwillseeinthefirstfewchapters,soitmightbeawhilebeforeyouencounterone. Semanticerrors Thethirdtypeoferroristhe [Link],itwillrunsuccessfullyinthesensethatthecomputerwillnot generateanyerrormessages,[Link],itwilldowhatyoutoldittodo. [Link](itssemantics)[Link] errorscanbetrickybecauseitrequiresyoutoworkbackwardbylookingattheoutputoftheprogramandtryingtofigureoutwhatitisdoing. Experimentaldebugging [Link],debuggingisoneofthemostintellectuallyrich,challenging,and interestingpartsofprogramming. Insomeways,[Link],andyouhavetoinfertheprocessesandeventsthatledtotheresultsyousee. [Link],[Link] wascorrect,thenyoucanpredicttheresultofthemodification,[Link],youhaveto [Link],Whenyouhaveeliminatedtheimpossible,whateverremains,howeverimprobable,mustbethe truth.([Link], TheSignofFour) Forsomepeople,[Link],programmingistheprocessofgraduallydebuggingaprogramuntilitdoeswhat [Link] somethingandmakesmallmodifications,debuggingthemasyougo,sothatyoualways haveaworkingprogram. Forexample,Linuxisanoperatingsystemthatcontainsthousandsoflinesofcode,butitstartedoutasasimpleprogramLinusTorvaldsusedtoexplorethe [Link],[Link] evolvedtoLinux.(TheLinuxUsersGuideBetaVersion1). Laterchapterswillmakemoresuggestionsaboutdebuggingandotherprogrammingpractices.

Formalandnaturallanguages
[Link]/wiki/Think_Python/Print_version 9/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Naturallanguagesarethelanguagespeoplespeak,suchasEnglish,Spanish,[Link](althoughpeopletrytoimpose someorderonthem)theyevolvednaturally. [Link],thenotationthatmathematiciansuseisaformal [Link] [Link]: Programminglanguagesareformallanguagesthathavebeendesignedtoexpresscomputations. [Link],3+3=6isasyntacticallycorrectmathematicalstatement,but3+=3$6isnot. H2O isasyntacticallycorrectchemicalformula,but 2Zzisnot. Syntaxrulescomeintwoflavors,pertainingto [Link],suchaswords,numbers,andchemical elements.Oneoftheproblemswith3+=3$6isthat $ isnotalegaltokeninmathematics(atleastasfarasIknow).Similarly, 2Zzisnotlegalbecause thereisnoelementwiththeabbreviation Zz. Thesecondtypeofsyntaxerrorpertainstothestructureofastatementthatis,thewaythetokensarearranged.Thestatement3+=3$6isillegalbecause eventhough+and=arelegaltokens,[Link],inachemicalformulathesubscriptcomesaftertheelementname, notbefore. Exercise1 [Link]. WhenyoureadasentenceinEnglishorastatementinaformallanguage,youhavetofigureoutwhatthestructureofthesentenceis(althoughinanatural languageyoudothissubconsciously).Thisprocessiscalled parsing. Forexample,whenyouhearthesentence,Thepennydropped,[Link] parsedasentence,youcanfigureoutwhatitmeans,[Link], youwillunderstandthegeneralimplicationofthissentence. Althoughformalandnaturallanguageshavemanyfeaturesincommontokens,structure,syntax,andsemanticstherearesomedifferences: ambiguity: Naturallanguagesarefullofambiguity,[Link] nearlyorcompletelyunambiguous,whichmeansthatanystatementhasexactlyonemeaning,regardlessofcontext. redundancy: Inordertomakeupforambiguityandreducemisunderstandings,[Link],theyareoftenverbose. Formallanguagesarelessredundantandmoreconcise. literalness: [Link],Thepennydropped,thereisprobablynopennyandnothingdropping[1].Formallanguages meanexactlywhattheysay.
[Link]/wiki/Think_Python/Print_version 10/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],thedifferencebetween formalandnaturallanguageislikethedifferencebetweenpoetryandprose,butmoreso: Poetry: Wordsareusedfortheirsoundsaswellasfortheirmeaning,[Link] onlycommonbutoftendeliberate. Prose: Theliteralmeaningofwordsismoreimportant,[Link] oftenambiguous. Programs: Themeaningofacomputerprogramisunambiguousandliteral,andcanbeunderstoodentirelybyanalysisofthetokensandstructure. Herearesomesuggestionsforreadingprograms(andotherformallanguages).First,rememberthatformallanguagesaremuchmoredensethannatural languages,[Link],thestructureisveryimportant,soitisusuallynotagoodideatoreadfromtoptobottom,lefttoright. Instead,learntoparsetheprograminyourhead,[Link],[Link] 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 ! '

Thisisanexampleofa printstatement[2],[Link],theresultisthe words


H e l l o ,W o r l d !

Thequotationmarksintheprogrammarkthebeginningandendofthetexttobedisplayedtheydontappearintheresult. SomepeoplejudgethequalityofaprogramminglanguagebythesimplicityoftheHello,World![Link],Pythondoesaboutaswellas possible.

Debugging
[Link], butifyouputthecodeintoascript,itiseasiertotryoutvariations.

[Link]/wiki/Think_Python/Print_version

Wheneveryouareexperimentingwithanewfeature,[Link],intheHello,world!program,whathappensifyouleave

11/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Wheneveryouareexperimentingwithanewfeature,[Link],intheHello,world!program,whathappensifyouleave outoneofthequotationmarks?Whatifyouleaveoutboth?Whatifyouspell p r i n t wrong? Thiskindofexperimenthelpsyourememberwhatyoureaditalsohelpswithdebugging,[Link] tomakemistakesnowandonpurposethanlaterandaccidentally. Programming,andespeciallydebugging,[Link],youmightfeelangry,despondentor embarrassed. Thereisevidencethatpeoplenaturallyrespondtocomputersasiftheywerepeople[3].Whentheyworkwell,wethinkofthemasteammates,andwhenthey areobstinateorrude,werespondtothemthesamewaywerespondtorude,obstinatepeople. [Link],likespeedand precision,andparticularweaknesses,likelackofempathyandinabilitytograspthebigpicture. Yourjobistobeagoodmanager:[Link] withtheproblem,withoutlettingyourreactionsinterferewithyourabilitytoworkeffectively. Learningtodebugcanbefrustrating,[Link] debuggingsection,likethisone,[Link]!

Glossary
problemsolving: Theprocessofformulatingaproblem,findingasolution,andexpressingthesolution. highlevellanguage: AprogramminglanguagelikePythonthatisdesignedtobeeasyforhumanstoreadandwrite. lowlevellanguage: Aprogramminglanguagethatisdesignedtobeeasyforacomputertoexecutealsocalledmachinelanguageorassemblylanguage. portability: Apropertyofaprogramthatcanrunonmorethanonekindofcomputer. interpret: Toexecuteaprograminahighlevellanguagebytranslatingitonelineatatime. compile: Totranslateaprogramwritteninahighlevellanguageintoalowlevellanguageallatonce,inpreparationforlaterexecution. sourcecode: Aprograminahighlevellanguagebeforebeingcompiled. objectcode: Theoutputofthecompilerafterittranslatestheprogram. executable: Anothernameforobjectcodethatisreadytobeexecuted.
[Link]/wiki/Think_Python/Print_version 12/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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.
[Link]/wiki/Think_Python/Print_version 13/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

printstatement: AninstructionthatcausesthePythoninterpretertodisplayavalueonthescreen.

Exercises
Exercise2 UseawebbrowsertogotothePythonwebsite,[Link] [Link],ifyouenter p r i n t inthesearchwindow,thefirstlinkthatappearsisthedocumentation ofthe p r i n t [Link],notallofitwillmakesensetoyou,butitisgoodtoknowwhereitis. Exercise3 StartthePythoninterpreterandtype'h e l p ( ) '[Link] h e l p ( ' p r i n t ' ) togetinformationaboutthe'p r i n t 'statement. Ifthis exampledoesntwork,youmayneedtoinstalladditionalPythondocumentationorsetanenvironmentvariablethedetailsdependonyouroperatingsystem andversionofPython. Exercise4 [Link] example,thesymbols'+ ',''and'/ 'denoteaddition,subtractionanddivision,[Link]'* '. 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,[Link] 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,[Link](andthe interpreter)canidentifystringsbecausetheyareenclosedinquotationmarks. Theprintstatementalsoworksforintegers.

[Link]/wiki/Think_Python/Print_version

14/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >p r i n t4 4

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 ' >

Notsurprisingly,stringsbelongtothetype s t r andintegersbelongtothetype i n t .Lessobviously,numberswithadecimalpointbelongtoatypecalled f l o a t , becausethesenumbersarerepresentedinaformatcalled floatingpoint.


> > >t y p e ( 3 . 2 ) < t y p e' f l o a t ' >

Whataboutvalueslike ' 1 7 ' and ' 3 . 2 ' ?Theylooklikenumbers,buttheyareinquotationmarkslikestrings.


> > >t y p e ( ' 1 7 ' ) < t y p e' s t r ' > > > >t y p e ( ' 3 . 2 ' ) < t y p e' s t r ' >

They'restrings. Whenyoutypealargeinteger,youmightbetemptedtousecommasbetweengroupsofthreedigits,asin 1 , 0 0 0 , 0 0 0 .ThisisnotalegalintegerinPython,butit islegal:


> > >p r i n t1 , 0 0 0 , 0 0 0 100

Well,thatsnotwhatweexpectedatall!Pythoninterprets 1 , 0 0 0 , 0 0 0 asacommaseparatedsequenceofintegers,whichitprintswithspacesbetween. Thisisthefirstexamplewehaveseenofasemanticerror:thecoderunswithoutproducinganerrormessage,butitdoesn'tdotherightthing.

Variables
Oneofthemostpowerfulfeaturesofaprogramminglanguageistheabilitytomanipulate [Link]. An assignmentstatementcreatesnewvariablesandgivesthemvalues:

[Link]/wiki/Think_Python/Print_version

15/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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

[Link] m e s s a g e thesecondgivestheinteger 1 7 to n thethirdassignsthe (approximate)valueofto p i . [Link] statediagram becauseitshowswhatstateeachofthevariablesisin(thinkofitasthevariablesstateofmind).Thisdiagramshowstheresultofthepreviousexample:


m e s s a g e n p i ' 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 ' 1 7 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:

[Link]/wiki/Think_Python/Print_version

16/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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

Canyoufigureoutwhatisgoingon?Hint:printthevalues 0 1 , 0 1 0 , 0 1 0 0 and 0 1 0 0 0 .

Variablenamesandkeywords
Programmersgenerallychoosenamesfortheirvariablesthataremeaningfultheydocumentwhatthevariableisusedfor. [Link],[Link],but itisagoodideatobeginvariablenameswithalowercaseletter(you'llseewhylater). Theunderscorecharacter(_ )[Link],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 ?

Itturnsoutthat c l a s s isoneofPython's [Link],andtheycannotbeusedas variablenames. Pythonhas31keywords:


a n d a s d e l e l i f f r o m n o t g l o b a lo r i f w h i l e w i t h

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

[Link]'tknowwhy,seeifitisonthislist.
[Link]/wiki/Think_Python/Print_version 17/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

IfyouwriteyourcodeinatexteditorthatunderstandsPython,youmayfindthatitmakesiteasyforyoutospotsuchkeywordclashesbydisplayingkeywords [Link] syntaxhighlighting,[Link] highlightingforitsexamplecode,sointhefollowingexample:


o k _ v a r i a b l e=4 2 y i e l d=4 2

youcanseethat y i e l d hasbeenrecognizedasakeywordandnotasanordinaryvariable,sinceitiscoloredorange.

Statements
[Link]:printandassignment. Whenyoutypeastatementininteractivemode,theinterpreterexecutesitanddisplaystheresult,ifthereisone. [Link],theresultsappearoneatatimeasthestatementsexecute. Forexample,thescript
p r i n t1 x=2 p r i n tx

producestheoutput
1 2

Theassignmentstatementproducesnooutput.

Operatorsandoperands
[Link] 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 )

Insomeotherlanguages, ^ isusedforexponentiation,[Link],butyou canreadaboutthemat w i k i . p y t h o n . o r g / m o i n / B i t w i s e O p e r a t o r s .


[Link]/wiki/Think_Python/Print_version 18/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thedivisionoperatormightnotdowhatyouexpect:
> > >m i n u t e=5 9 > > >m i n u t e / 6 0 0

Thevalueof m i n u t e is59,andinconventionalarithmetic59dividedby60is0.98333,[Link] floor division. [1] Whenbothoftheoperandsareintegers,theresultisalsoanintegerfloordivisionchopsoffthefractionpart,sointhisexampleitroundsdowntozero. Ifeitheroftheoperandsisafloatingpointnumber,Pythonperformsfloatingpointdivision,andtheresultisa f l o a t :


> > >m i n u t e / 6 0 . 0 0 . 9 8 3 3 3 3 3 3 3 3 3 3 3 3 3 2 8

Expressions
An expressionisacombinationofvalues,variables,[Link],andsoisavariable,sothefollowingare alllegalexpressions(assumingthatthevariable x hasbeenassignedavalue):
1 7 x x+1 7

Ifyoutypeanexpressionininteractivemode,theinterpreter evaluatesitanddisplaystheresult:
> > >1+1 2

Butinascript,anexpressionallbyitselfdoesntdoanything!Thisisacommonsourceofconfusionforbeginners. Exercise2 TypethefollowingstatementsinthePythoninterpretertoseewhattheydo:


5 x=5 x+1

[Link]/wiki/Think_Python/Print_version

19/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link]?Modifythescriptbytransformingeachexpressionintoaprintstatementandthen runitagain.

Orderofoperations
Whenmorethanoneoperatorappearsinanexpression,theorderofevaluationdependsonthe [Link],Python [Link] PEMDAS isausefulwaytoremembertherules: P [Link] areevaluatedfirst, 2*( 3 1 ) is4,and ( 1 + 1 ) * * ( 5 2 ) [Link],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,[Link] 2 * 3 1 is 5,not4,and 6 + 4 / 2 is8,not5. [Link] 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 '

The + operatorworkswithstrings,butitmightnotdowhatyouexpect:itperforms concatenation,whichmeansjoiningthestringsbylinkingthemendtoend. Forexample:


f i r s t=' t h r o a t ' s e c o n d=' w a r b l e r ' p r i n tf i r s t+s e c o n d

Theoutputofthisprogramis t h r o a t w a r b l e r . The * [Link], S p a m * 3 is ' S p a m S p a m S p a m ' .Ifoneoftheoperandsisastring,theotherhastobean integer. Thisuseof + and * [Link] 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 ' ,[Link],thereisasignificantwayinwhichstringconcatenationandrepetitionaredifferentfromintegeradditionand [Link]?

Comments
[Link]/wiki/Think_Python/Print_version 20/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Asprogramsgetbiggerandmorecomplicated,[Link],anditisoftendifficulttolookatapieceofcode andfigureoutwhatitisdoing,orwhy. Forthisreason,[Link] comments, andtheystartwiththe # symbol:


#c o m p u t et h ep e r c e n t a g eo ft h eh o u rt h a th a se l a p s e d p e r c e n t a g e=( m i n u t e*1 0 0 )/6 0

Inthiscase,[Link]:
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

Everythingfromthe # totheendofthelineisignoredithasnoeffectontheprogram. [Link] what thecode doesitismuchmoreusefultoexplain why. Thiscommentisredundantwiththecodeanduseless:


v=5 #a s s i g n5t ov

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

Forsyntaxerrors,[Link] 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 ,neitherofwhich isveryinformative.


[Link]/wiki/Think_Python/Print_version 21/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Theruntimeerroryouaremostlikelytomakeisausebeforedefthatis,[Link] 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

Variablesnamesarecasesensitive,so L a T e X isnotthesameas l a t e x . [Link],toevaluate1/2,youmightbetemptedtowrite


> > >1 . 0/2 . 0*p i

Butthedivisionhappensfirst,soyouwouldget/2,whichisnotthesamething!ThereisnowayforPythontoknowwhatyoumeanttowrite,sointhis caseyoudontgetanerrormessageyoujustgetthewronganswer.

Glossary
value: Oneofthebasicunitsofdata,likeanumberorstring,thataprogrammanipulates. type: [Link](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: [Link],thestatementswehaveseenareassignmentsandprintstatements. assignment: Astatementthatassignsavaluetoavariable. statediagram: Agraphicalrepresentationofasetofvariablesandthevaluestheyreferto. keyword:
[Link]/wiki/Think_Python/Print_version 22/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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.

[Link]/wiki/Think_Python/Print_version

23/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Exercise4 PracticeusingthePythoninterpreterasacalculator: Thevolumeofaspherewithradius'r'is'4/3'r3. Whatisthevolumeofaspherewithradius5?Hint:392.6iswrong! Supposethecoverpriceofabookis$24.95,butbookstoresgeta 40%[Link]$3forthefirstcopyand75centsforeachadditionalcopy.Whatisthetotalwholesalecostfor60copies? IfIleavemyhouseat6:52amandrun1mileataneasypace (8:15permile),then3milesattempo(7:12permile)and1mileateasypaceagain,whattimedoIgethomeforbreakfast?

Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.

Functions
Functioncalls
Inthecontextofprogramming,a [Link],youspecifythe [Link],youcan"call"[Link] functioncall :

> > >t y p e ( 3 2 ) < t y p e' i n t ' >

[Link] [Link],forthisfunction,isthetypeofthe argument. Itiscommontosaythatafunction"takes"anargumentand"returns"[Link] returnvalue.

Typeconversionfunctions
[Link],ifitcan,or complainsotherwise:

[Link]/wiki/Think_Python/Print_version

24/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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 [Link],yougetsomeinformationaboutit:

> > >p r i n tm a t h < m o d u l e' m a t h 'f r o m' / u s r / l i b / p y t h o n 2 . 5 / l i b d y n l o a d / m a t h . s o ' >


[Link]/wiki/Think_Python/Print_version 25/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],youhavetospecifythenameofthemodule andthenameofthefunction,separatedbyadot(alsoknownasaperiod).Thisformatiscalled dotnotation.

> > >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 )

[Link] basee. [Link](cos,tan,etc.)takearguments [Link],divideby360andmultiplyby2:

> > >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

[Link],accuratetoabout15digits. Ifyouknowyourtrigonometry,youcancheckthepreviousresultbycomparingittothesquarerootoftwodividedbytwo:

> > >m a t h . s q r t ( 2 )/2 . 0 0 . 7 0 7 1 0 6 7 8 1 1 8 7

Composition
Sofar,wehavelookedattheelementsofaprogramvariables,expressions,andstatementsinisolation,withouttalkingabouthowtocombinethem. Oneofthemostusefulfeaturesofprogramminglanguagesistheirabilitytotakesmallbuildingblocksand [Link],theargumentofa functioncanbeanykindofexpression,includingarithmeticoperators:
[Link]/wiki/Think_Python/Print_version 26/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

x=m a t h . s i n ( d e g r e e s/3 6 0 . 0*2*m a t h . p i )

Andevenfunctioncalls:

x=m a t h . e x p ( m a t h . l o g ( x + 1 ) )

Almostanywhereyoucanputavalue,youcanputanarbitraryexpression,withoneexception:theleftsideofanassignmentstatementhastobeavariable [Link].
> > >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 . "

[Link] p r i n t _ l y r i c s .Therulesforfunctionnamesarethesameasfor variablenames:letters,numbersandsomepunctuationmarksarelegal,butthefirstcharactercan'[Link]'tuseakeywordasthenameofa function,andyoushouldavoidhavingavariableandafunctionwiththesamename. Theemptyparenthesesafterthenameindicatethatthisfunctiondoesn'ttakeanyarguments. Thefirstlineofthefunctiondefinitioniscalledthe headertherestiscalledthe [Link]. Byconvention,theindentationisalwaysfourspaces(seeSection).Thebodycancontainanynumberofstatements. [Link] 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 . "
[Link]/wiki/Think_Python/Print_version 27/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

. . . . . .

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 . "

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 ' >

Thevalueof p r i n t _ l y r i c s isa functionobject,whichhastype ' f u n c t i o n ' . Thesyntaxforcallingthenewfunctionisthesameasforbuiltinfunctions:

> > >p r i n 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 .

Onceyouhavedefinedafunction,[Link],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.
[Link]/wiki/Think_Python/Print_version 28/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Definitionsanduses
Pullingtogetherthecodefragmentsfromtheprevioussection,thewholeprogramlookslikethis:

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 . " 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 ( ) r e p e a t _ l y r i c s ( )

Thisprogramcontainstwofunctiondefinitions: p r i n t _ l y r i c s and r e p e a t _ l y r i c s .Functiondefinitionsgetexecutedjustlikeotherstatements,buttheeffectisto [Link],andthefunctiondefinitiongeneratesnooutput. Asyoumightexpect,[Link],thefunctiondefinitionhastobeexecutedbeforethefirsttimeit iscalled.

Exercise1
Movethelastlineofthisprogramtothetop,[Link].

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. [Link],inorderfromtoptobottom. Functiondefinitionsdonotaltertheflowofexecutionoftheprogram,butrememberthatstatementsinsidethefunctionarenotexecuteduntilthefunctionis called. [Link],theflowjumpstothebodyofthefunction,executesallthe statementsthere,andthencomesbacktopickupwhereitleftoff.
[Link]/wiki/Think_Python/Print_version 29/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thatsoundssimpleenough,[Link],theprogrammighthavetoexecute [Link],theprogrammighthavetoexecuteyetanotherfunction! Fortunately,Pythonisgoodatkeepingtrackofwhereitis,soeachtimeafunctioncompletes,theprogrampicksupwhereitleftoffinthefunctionthatcalled [Link],itterminates. What'sthemoralofthissordidtale?Whenyoureadaprogram,youdon'[Link] followtheflowofexecution.

Parametersandarguments
[Link],[Link] takemorethanoneargument:[Link],thebaseandtheexponent. Insidethefunction,theargumentsareassignedtovariablescalled [Link]:

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

[Link],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 :
[Link]/wiki/Think_Python/Print_version 30/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >p r i n t _ t w i c e ( ' S p a m' * 4 ) S p a mS p a mS p a mS p a m S p a mS p a mS p a mS p a m > > >p r i n t _ t w i c e ( m a t h . c o s ( m a t h . p i ) ) 1 . 0 1 . 0

Theargumentisevaluatedbeforethefunctioniscalled,sointheexamplestheexpressions ' S p a m' * 4 [Link]([Link])areonlyevaluatedonce. Youcanalsouseavariableasanargument:

> > >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 .

Thenameofthevariablewepassasanargument(michael)hasnothingtodowiththenameoftheparameter(bruce).Itdoesn'tmatterwhatthevaluewas calledbackhome(inthecaller)herein p r i n t _ t w i c e ,wecalleverybodybruce.

Variablesandparametersarelocal
Whenyoucreateavariableinsideafunction,itis local ,[Link]:

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,[Link]:

> > >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 )
[Link]/wiki/Think_Python/Print_version 31/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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,[Link],wegetanexception:

> > >p r i n tc a t N a m e E r r o r :n a m e' c a t 'i sn o td e f i n e d

[Link],outside p r i n t _ t w i c e ,thereisnosuchthingasbruce.

Stackdiagrams
Tokeeptrackofwhichvariablescanbeusedwhere,itissometimesusefultodrawa [Link],stackdiagramsshowthevalueof eachvariable,buttheyalsoshowthefunctioneachvariablebelongsto. Eachfunctionisrepresentedbya [Link] stackdiagramforthepreviousexamplelookslikethis: File:[Link],[Link], 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 _ _ ,[Link], itbelongsto _ _ m a i n _ _ . [Link],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 ) :
[Link]/wiki/Think_Python/Print_version 32/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

F i l e" t e s t . p y " ,l i n e1 3 ,i n_ _ m a i n _ _ c a t _ t w i c e ( l i n e 1 ,l i n e 2 ) F i l e" t e s t . p y " ,l i n e5 ,i nc a t _ t w i c e p r i n t _ t w i c e ( c a t ) F i l e" t e s t . p y " ,l i n e9 ,i np r i n t _ t w i c e p r i n tc a t N a m e E r r o r :n a m e' c a t 'i sn o td e f i n e d

Thislistoffunctionsiscalleda [Link],andwhatline,[Link] alsoshowsthelineofcodethatcausedtheerror. [Link].

Fruitfulfunctionsandvoidfunctions
Someofthefunctionsweareusing,suchasthemathfunctions,yieldresultsforlackofabettername,Icallthem fruitful [Link],like p r i n t _ t w i c e ,performanactionbutdon'[Link] voidfunctions. Whenyoucallafruitfulfunction,youalmostalwayswanttodosomethingwiththeresultforexample,youmightassignittoavariableoruseitaspartofan expression:

x=m a t h . c o s ( r a d i a n s ) g o l d e n=( m a t h . s q r t ( 5 )+1 )/2

Whenyoucallafunctionininteractivemode,Pythondisplaystheresult:

> > >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

Butinascript,ifyoucallafruitfulfunctionallbyitself,thereturnvalueislostforever!

m a t h . s q r t ( 5 )

[Link]/wiki/Think_Python/Print_version

33/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thisscriptcomputesthesquarerootof5,butsinceitdoesn'tstoreordisplaytheresult,itisnotveryuseful. Voidfunctionsmightdisplaysomethingonthescreenorhavesomeothereffect,buttheydon'[Link], yougetaspecialvaluecalledNone.

> > >r e s u l t=p r i n t _ t w i c e ( ' B i n g ' ) B i n g B i n g > > >p r i n tr e s u l t N o n e

ThevalueNoneisnotthesameasthestring ' N o n e ' .Itisaspecialvaluethathasitsowntype:

> > >p r i n tt y p e ( N o n e ) < t y p e' N o n e T y p e ' >

[Link].

Whyfunctions?
[Link]: Creatinganewfunctiongivesyouanopportunitytonameagroupofstatements,whichmakesyourprogrameasiertoreadanddebug. [Link],ifyoumakeachange,youonlyhavetomakeitinoneplace. Dividingalongprogramintofunctionsallowsyoutodebugthepartsoneatatimeandthenassemblethemintoaworkingwhole. [Link],youcanreuseit.

Debugging
Ifyouareusingatexteditortowriteyourscripts,[Link] exclusively(notabs).MosttexteditorsthatknowaboutPythondothisbydefault,butsomedon't. Tabsandspacesareusuallyinvisible,whichmakesthemhardtodebug,sotrytofindaneditorthatmanagesindentationforyou.

[Link]/wiki/Think_Python/Print_version

34/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Also,don'[Link],butsomedon'[Link] arelookingatinthetexteditorisnotthesameastheprogramyouarerunning. Debuggingcantakealongtimeifyoukeeprunningthesame,incorrect,programoverandover! [Link]'renotsure,putsomethinglike p r i n t' h e l l o ' atthebeginningoftheprogramand [Link]'tsee h e l l o ,you'renotrunningtherightprogram!

Glossary
function:Anamedsequenceofstatementsthatperformssome [Link]. functiondefinition:Astatementthatcreatesanewfunction, specifyingitsname,parameters,andthestatementsitexecutes. functionobject:Avaluecreatedbyafunctiondefinition. Thenameofthefunctionisavariablethatreferstoafunctionobject. header:Thefirstlineofafunctiondefinition. body:Thesequenceofstatementsinsideafunctiondefinition. parameter:Anameusedinsideafunctiontorefertothevalue passedasanargument. functioncall:[Link] consistsofthefunctionnamefollowedbyanargumentlist. argument:Avalueprovidedtoafunctionwhenthefunctioniscalled. Thisvalueisassignedtothecorrespondingparameterinthefunction. localvariable:[Link] variablecanonlybeusedinsideitsfunction.
[Link]/wiki/Think_Python/Print_version 35/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

returnvalue:[Link] 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
[Link]/wiki/Think_Python/Print_version 36/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link], d o _ t w i c e isafunctionthattakesafunctionobjectasan argumentandcallsittwice:

' ' d e fd o _ t w i c e ( f ) : f ( ) f ( ) ' '

Heresanexamplethatuses d o _ t w i c e tocallafunctionnamed p r i n t _ s p a m twice.

' ' d e fp r i n t _ s p a m ( ) : p r i n t' s p a m ' d o _ t w i c e ( p r i n t _ s p a m ) ' '

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,[Link] shouldbeonlytwostatementsinthebodyofthisfunction,notfour. [Link]/code/do_four.py.
[Link]/wiki/Think_Python/Print_version 37/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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' '' '

Theoutputofthesestatementsis ' +' . Aprintstatementallbyitselfendsthecurrentlineandgoestothenextline. 1. Usethepreviousfunctiontodrawasimilargridwithfourrowsandfourcolumns. [Link]/code/[Link]. [Link], PracticalCProgramming,ThirdEdition,OReilly(1997)

Casestudy:interfacedesign
TurtleWorld

[Link]/wiki/Think_Python/Print_version

Toaccompanythisbook,[Link],whichprovidesasetoffunctionsfordrawing 38/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Toaccompanythisbook,[Link],whichprovidesasetoffunctionsfordrawing linesbysteeringturtlesaroundthescreen. YoucandownloadSwampyfrom t h i n k p y t h o n . c o m / s w a m p y( h t t p : / / t h i n k p y t h o n . c o m / s w a m p y ) followtheinstructionstheretoinstallSwampyonyoursystem. Moveintothedirectorythatcontains T u r t l e W o r l d . p y ,createafilenamed p o l y g o n . p y andtypeinthefollowingcode:


f r o mT u r t l e W o r l di m p o r t* w o r l d=T u r t l e W o r l d ( ) b o b=T u r t l e ( ) p r i n tb o b w a i t _ f o r _ u s e r ( )

Thefirstlineisavariationofthe i m p o r t statementwesawbeforeinsteadofcreatingamoduleobject,itimportsthefunctionsfromthemoduledirectly,soyou canaccessthemwithoutusingdotnotation. ThenextlinescreateaTurtleWorldassignedto w o r l d andaTurtleassignedto b o b .Printing b o b yieldssomethinglike:


< T u r t l e W o r l d . T u r t l ei n s t a n c ea t0 x b 7 b f b f 4 c >

Thismeansthat b o b referstoan instanceofaTurtleasdefinedinmodule T u r t l e W o r l d .Inthiscontext,"instance"meansamemberofasetthisTurtleisoneof thesetofpossibleTurtles.


w a i t _ f o r _ u s e r tellsTurtleWorldtowaitfortheusertodosomething,althoughinthiscasethere'snotmuchfortheusertodoexceptclosethewindow.

TurtleWorldprovidesseveralturtlesteeringfunctions: f d and b k forforwardandbackward,and l t and r t [Link],eachTurtleisholdinga pen,whichiseitherdownorupifthepenisdown,[Link] 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 )

Thefirstlinetells b o b [Link]. Whenyourunthisprogram,youshouldsee b o b moveeastandthensouth,leavingtwolinesegmentsbehind. [Link]'vegotitworking!

Simplerepetition
[Link]/wiki/Think_Python/Print_version 39/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Wecandothesamethingmoreconciselywitha f o r [Link] p o l y g o n . p y andrunitagain:

f o rii nr a n g e ( 4 ) : p r i n t' H e l l o ! '

Youshouldseesomethinglikethis:
H e l l o ! H e l l o ! H e l l o ! H e l l o !

Thisisthesimplestuseofthe f o r [Link] pageuntilyoudo. Hereisa f o r statementthatdrawsasquare:


f o rii nr a n g e ( 4 ) : f d ( b o b ,1 0 0 ) l t ( b o b )

Thesyntaxofa f o r [Link] numberofstatements. A f o r statementissometimescalleda [Link],itrunsthebody fourtimes.


[Link]/wiki/Think_Python/Print_version 40/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link] extraturntakesalittlemoretime,[Link] turtlebackinthestartingposition,facinginthestartingdirection.

Exercises
[Link],buttheyhaveapoint,[Link],thinkabout whatthepointis. Thefollowingsectionshavesolutionstotheexercises,sodontlookuntilyouhavefinished(oratleasttried). Writeafunctioncalled s q u a r e thattakesaparameter named t ,[Link] 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 ,[Link] witharangeofvaluesfor l e n g t h . Thefunctions l t and r t make90degreeturnsby default,[Link], l t ( b o b ,4 5 ) turns b o b [Link] s q u a r e andchangethenameto p o l y g o n .Addanotherparameternamed n [Link]:Theanglesofann sidedregularpolygonare360.0/ ndegrees.

Writeafunctioncalled c i r c l e thattakesaturtle, t , andradius, r ,asparametersandthatdrawsanapproximatecirclebyinvoking p o l y g o n [Link] rangeofvaluesof r .

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
[Link]/wiki/Think_Python/Print_version 41/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

thattakesanadditionalparameter a n g l e ,whichdetermineswhatfractionofacircletodraw. a n g l e isinunitsofdegrees,sowhen a n g l e = 3 6 0 , a r c shoulddrawa completecircle.

Encapsulation
Thefirstexerciseasksyoutoputyoursquaredrawingcodeintoafunctiondefinitionandthencallthefunction,[Link] 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,[Link], 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 )

Wrappingapieceofcodeupinafunctioniscalled [Link],whichserves [Link],itismoreconcisetocallafunctiontwicethantocopyandpastethebody!

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 )

Addingaparametertoafunctioniscalled generalizationbecauseitmakesthefunctionmoregeneral:inthepreviousversion,thesquareisalwaysthesame sizeinthisversionitcanbeanysize. [Link], p o l y g o n [Link]:


[Link]/wiki/Think_Python/Print_version 42/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

d e fp o l y g o n ( t ,n ,l e n g t h ) : a n g l e=3 6 0 . 0/n 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 ) p o l y g o n ( b o b ,7 ,7 0 )

[Link],itiseasytoforgetwhattheyare,orwhatordertheyshould [Link],andsometimeshelpful,toincludethenamesoftheparametersintheargumentlist:
p o l y g o n ( b o b ,n = 7 ,l e n g t h = 7 0 )

Thesearecalled keywordargumentsbecausetheyincludetheparameternamesaskeywords(nottobeconfusedwithPythonkeywordslike w h i l e and d e f ). [Link]:whenyoucallafunction,theargumentsare assignedtotheparameters.

Interfacedesign
Thenextstepistowrite c i r c l e ,whichtakesaradius, r ,[Link] 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 )

Thefirstlinecomputesthecircumferenceofacirclewithradius r usingtheformula2 [Link] m a t h . p i ,wehavetoimport m a t h .Byconvention, i m p o r t statementsareusuallyatthebeginningofthescript.


n isthenumberoflinesegmentsinourapproximationofacircle,so l e n g t h [Link], p o l y g o n drawsa50sidespolygonthat

approximatesacirclewithradius r . Onelimitationofthissolutionisthat n isaconstant,whichmeansthatforverybigcircles,thelinesegmentsaretoolong,andforsmallcircles,wewastetime [Link] n [Link](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.
[Link]/wiki/Think_Python/Print_version 43/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Nowthenumberofsegmentsis(approximately) c i r c u m f e r e n c e / 3 ,sothelengthofeachsegmentis(approximately)3,whichissmallenoughthatthecircleslook good,butbigenoughtobeefficient,andappropriateforanysizecircle.

Refactoring
WhenIwrote c i r c l e ,Iwasabletoreuse p o l y g o n [Link] 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 )

Thesecondhalfofthisfunctionlookslike p o l y g o n ,butwecantreuse p o l y g o n [Link] p o l y g o n totakeanangleasa thirdargument,butthen p o l y g o n wouldnolongerbeanappropriatename!Instead,letscallthemoregeneralfunction p o l y l i n e :


d e fp o l y l i n e ( t ,n ,l e n g t h ,a n g 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 )

Nowwecanrewrite p o l y g o n and a r c touse p o l y l i n e :


d e fp o l y g o n ( t ,n ,l e n g t h ) : a n g l e=3 6 0 . 0/n p o l y l i n e ( t ,n ,l e n g t h ,a n g l e ) d e fa r c ( t ,r ,a n g l e ) :
[Link]/wiki/Think_Python/Print_version 44/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 p o l y l i n e ( t ,n ,s t e p _ l e n g t h ,s t e p _ a n g l e )

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 )

Thisprocessrearrangingaprogramtoimprovefunctioninterfacesandfacilitatecodereuseiscalled [Link],wenoticedthattherewas similarcodein a r c and p o l y g o n ,sowefactoreditoutinto p o l y l i n e . Ifwehadplannedahead,wemighthavewritten p o l y l i n e firstandavoidedrefactoring,butoftenyoudontknowenoughatthebeginningofaprojecttodesign [Link],[Link].

Adevelopmentplan
A [Link] are: Startbywritingasmallprogramwithnofunctiondefinitions. Onceyougettheprogramworking,encapsulateitinafunction andgiveitaname. Generalizethefunctionbyaddingappropriateparameters. Repeatsteps13untilyouhaveasetofworkingfunctions. Copyandpasteworkingcodetoavoidretyping(andredebugging). Lookforopportunitiestoimprovetheprogrambyrefactoring. Forexample,ifyouhavesimilarcodeinseveralplaces,considerfactoringitintoanappropriatelygeneralfunction. Thisprocesshassomedrawbackswewillseealternativeslaterbutitcanbeusefulifyoudontknowaheadoftimehowtodividetheprograminto [Link].

docstring

[Link]/wiki/Think_Python/Print_version

45/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Thisdocstringisatriplequotedstring,alsoknownasamultilinestringbecausethetriplequotesallowthestringtospanmorethanoneline. Itisterse,[Link](withoutgettinginto thedetailsofhowitdoesit).Itexplainswhateffecteachparameterhasonthebehaviorofthefunctionandwhattypeeachparametershouldbe(ifitisnot obvious). [Link] explainingoneofyourfunctions,thatmightbeasignthattheinterfacecouldbeimproved.

Debugging
[Link]. Forexample, p o l y l i n e [Link](orsomeotherobjectthatworkswith f d and l t ).Thesecondhastobeanumber, anditshouldprobablybepositive,[Link] r a n g e complains otherwise(dependingonwhichversionofPythonyouarerunning).Thefourthhastobeanumber,whichisunderstoodtobeindegrees. Theserequirementsarecalled [Link],conditionsattheendof thefunctionare [Link](likedrawinglinesegments)andanysideeffects(likemovingthe TurtleormakingotherchangesintheWorld). [Link](properlydocumented!)preconditionandthefunctiondoesntworkcorrectly,thebugis inthecaller,[Link],forpurposesofdebuggingitisoftenagoodideaforfunctionstochecktheirpreconditionsratherthanassumetheyare [Link],thenifsomethinggoeswrong,youwillknowwhichfunctiontoblame.

Glossary
instance: [Link]. loop: Apartofaprogramthatcanexecuterepeatedly. encapsulation: Theprocessoftransformingasequenceofstatementsintoafunctiondefinition.
[Link]/wiki/Think_Python/Print_version 46/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 [Link],theturtleendsupafewunitsawayfromthecorrect [Link],youmightsee howitworks. Exercise2 Writeanappropriatelygeneralsetoffunctionsthat candrawflowerslikethis: <IMGSRC="[Link]"> 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:
[Link]/wiki/Think_Python/Print_version 47/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

<IMGSRC="[Link]"> 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,[Link] 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 [Link],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. [Link],youcancheckwhetheronenumberisdivisiblebyanotherif x%y iszero,then x is divisibleby y . Also,[Link], x%1 0 yieldstherightmostdigitof x (inbase10).Similarly x%1 0 0 yieldsthe lasttwodigits.

Booleanexpressions
A [Link] = = ,whichcomparestwooperandsandproduces T r u e iftheyareequaland F a l s e otherwise:
> > >5= =5 T r u e
[Link]/wiki/Think_Python/Print_version 48/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >5= =6 F a l s e


T r u e and F a l s e arespecialvaluesthatbelongtothetype b o o l theyarenotstrings:

> > >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 ' >

The = = operatorisoneofthe comparisonoperatorstheothersare:


x! =y x>y x<y x> =y x< =y #xi sn o te q u a lt oy #xi sg r e a t e rt h a ny #xi sl e s st h a ny #xi sg r e a t e rt h a no re q u a lt oy #xi sl e s st h a no re q u a lt oy

Althoughtheseoperationsareprobablyfamiliartoyou,[Link] equalsign(= )insteadofadoubleequalsign(= = ).Rememberthat = isanassignmentoperatorand = = [Link] = < or = > .

Logicaloperators
Therearethree logicaloperators: a n d , o r ,and n o t .Thesemantics(meaning)[Link], x>0a n dx <1 0 istrueonlyif x isgreaterthan0 andlessthan10.
n % 2= =0o rn % 3= =0 istrueif eitheroftheconditionsistrue,thatis,ifthenumberisdivisibleby2 or3.

Finally,the n o t operatornegatesabooleanexpression,so n o t( x>y ) istrueif x>y isfalse,thatis,if x islessthanorequalto y . Strictlyspeaking,theoperandsofthelogicaloperatorsshouldbebooleanexpressions,[Link] true.


> > >1 7a n dT r u e T r u e

Thisflexibilitycanbeuseful,[Link](unlessyouknowwhatyouaredoing).

Conditionalexecution
Inordertowriteusefulprograms,wealmostalwaysneedtheabilitytocheckconditionsandchangethebehavioroftheprogramaccordingly. Conditional

[Link]/wiki/Think_Python/Print_version

49/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Inordertowriteusefulprograms,wealmostalwaysneedtheabilitytocheckconditionsandchangethebehavioroftheprogramaccordingly. Conditional [Link] i f statement:


i fx>0 : p r i n t' xi sp o s i t i v e '

Thebooleanexpressionafterthe i f statementiscalledthe [Link],[Link],nothinghappens.


i f statementshavethesamestructureasfunctiondefinitions:[Link] compoundstatements.

Thereisnolimitonthenumberofstatementsthatcanappearinthebody,[Link],itisusefultohaveabodywithno statements(usuallyasaplacekeeperforcodeyouhaven'twrittenyet).Inthatcase,youcanusethe p a s s statement,whichdoesnothing.


i fx<0 : p a s s

#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,[Link] 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 '

Iftheremainderwhen x isdividedby2is0,thenweknowthat x iseven,[Link],the [Link],[Link] branches,becausetheyarebranchesintheflowofexecution.

Chainedconditionals
[Link] 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 '

e l i f [Link],[Link] e l i f [Link] e l s e clause,it50/282 [Link]/wiki/Think_Python/Print_version

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

e l i f [Link],[Link] e l i f [Link] e l s e clause,it

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 ( )

[Link],thenextischecked,[Link],thecorrespondingbranchexecutes,andthe [Link],onlythefirsttruebranchexecutes.

Nestedconditionals
[Link]:
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 '

[Link] i f statement,whichhastwo [Link],althoughtheycouldhavebeenconditionalstatementsaswell. Althoughtheindentationofthestatementsmakesthestructureapparent, [Link],itisagood ideatoavoidthemwhenyoucan. [Link],wecanrewritethefollowingcodeusingasingleconditional:


i f0<x : i fx<1 0 : p r i n t' xi sap o s i t i v es i n g l e d i g i tn u m b e r . '

The p r i n t statementisexecutedonlyifwemakeitpastbothconditionals,sowecangetthesameeffectwiththe a n d operator:


i f0<xa n dx<1 0 : p r i n t' xi sap o s i t i v es i n g l e d i g i tn u m b e r . '

[Link]/wiki/Think_Python/Print_version

51/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Recursion
[Link],butitturnsouttobeoneof [Link],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 )

If n is0ornegative,itoutputstheword,Blastoff!Otherwise,itoutputs n andthencallsafunctionnamed c o u n t d o w n itselfpassing n 1 asanargument. Whathappensifwecallthisfunctionlikethis?


> > >c o u n t d o w n ( 3 )

Theexecutionof c o u n t d o w n beginswith n = 3 ,andsince n isgreaterthan0,itoutputsthevalue3,andthencallsitself... Theexecutionof c o u n t d o w n beginswith n = 2 ,andsince


n isgreaterthan0,itoutputsthevalue2,andthencallsitself...

Theexecutionof c o u n t d o w n beginswith n = 1 ,andsince


n isgreaterthan0,itoutputsthevalue1,andthencallsitself...

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 !
[Link]/wiki/Think_Python/Print_version 52/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Afunctionthatcallsitselfis recursivetheprocessiscalled recursion. Asanotherexample,wecanwriteafunctionthatprintsastring n times.


d e fp r i n t _ n ( s ,n ) : i fn< =0 : r e t u r n p r i n ts p r i n t _ n ( s ,n 1 )

If n< =0 the r e t u r n [Link],andtheremaininglinesofthefunctionarenot executed. Therestofthefunctionissimilarto c o u n t d o w n :if n isgreaterthan0,itdisplays s andthencallsitselftodisplay s [Link] outputis 1+( n-1 ) ,whichaddsupto n . Forsimpleexampleslikethis,itisprobablyeasiertousea f o r [Link] f o r loopandeasytowritewith recursion,soitisgoodtostartearly.

Stackdiagramsforrecursivefunctions
InSection3.10,[Link] function. Everytimeafunctiongetscalled,Pythoncreatesanewfunctionframe,[Link], theremightbemorethanoneframeonthestackatthesametime. Thisfigureshowsastackdiagramfor c o u n t d o w n calledwith n=3 : <IMGSRC="[Link]"> 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 [Link] 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,[Link] infiniterecursion, [Link]:
[Link]/wiki/Think_Python/Print_version 53/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

d e fr e c u r s e ( ) : r e c u r s e ( )

Inmostprogrammingenvironments,[Link] 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

[Link],thereare1000 r e c u r s e framesonthestack!

Keyboardinput
[Link]. Pythonprovidesabuiltinfunctioncalled r a w _ i n p u t thatgetsinputfromthekeyboard[1].Whenthisfunctioniscalled,theprogramstopsandwaitsfortheuserto [Link],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 !

Thesequence \ n attheendofthepromptrepresentsa newline,[Link] belowtheprompt. Ifyouexpecttheusertotypeaninteger,youcantrytoconvertthereturnvalueto i n t :


[Link]/wiki/Think_Python/Print_version 54/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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 [Link]: Whatkindoferroritwas,and Whereitoccurred. Syntaxerrorsareusuallyeasytofind,[Link] 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

Inthisexample,[Link] y ,[Link],error messagesindicatewheretheproblemwasdiscovered,buttheactualerrormightbeearlierinthecode,sometimesonapreviousline. [Link] SNRdb=10log10(P signal/ P noise).In Python,youmightwritesomethinglikethis:


i m p o r tm a t h
[Link]/wiki/Think_Python/Print_version 55/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

s i g n a l _ p o w e r=9 n o i s e _ p o w e r=1 0 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 ) p r i n td e c i b e l s

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

Theerrormessageindicatesline5,[Link],itmightbeusefultoprintthevalueof r a t i o ,whichturnsout tobe0.Theproblemisinline4,[Link] values. Ingeneral,errormessagestellyouwheretheproblemwasdiscovered,butthatisoftennotwhereitwascaused.

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: [Link](:).Thebodyisindentedrelativetotheheader. body: Thesequenceofstatementswithinacompoundstatement. branch: Oneofthealternativesequencesofstatementsinaconditionalstatement.
[Link]/wiki/Think_Python/Print_version 56/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

chainedconditional: Aconditionalstatementwithaseriesofalternativebranches. nestedconditional: Aconditionalstatementthatappearsinoneofthebranchesofanotherconditionalstatement. recursion: Theprocessofcallingthefunctionthatiscurrentlyexecuting. basecase: Aconditionalbranchinarecursivefunctionthatdoesnotmakearecursivecall. infiniterecursion: [Link],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 '[Link] '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,[Link],ifoneofthesticksis12incheslongandthe othertwoareoneinchlong,[Link],thereisasimpletesttosee ifitispossibletoformatriangle: Ifanyofthethreelengthsisgreaterthanthesumoftheothertwo,[Link],youcan[2]. Writeafunctionnamed i s _ t r i a n g l e thattakesthree

[Link]/wiki/Think_Python/Print_version

57/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

integersasarguments,andthatprintseitherYesorNo,dependingonwhetheryoucanorcannotformatrianglefromstickswiththegivenlengths. Writeafunctionthatpromptstheusertoinputthreestick lengths,convertsthemtointegers,anduses i s _ t r i a n g l e tocheckwhetherstickswiththegivenlengthscanformatriangle. ThefollowingexercisesuseTurtleWorldfromChapter4: Exercise3 Readthefollowingfunctionandseeifyoucanfigureout [Link](seetheexamplesinChapter'4').


' ' d e fd r a w ( t ,l e n g t h ,n ) : i fn= =0 : r e t u r n a n g l e=5 0 f d ( t ,l e n g t h * n ) l t ( t ,a n g l e ) d r a w ( t ,l e n g t h ,n 1 ) r t ( t ,2 * a n g l e ) d r a w ( t ,l e n g t h ,n 1 ) l t ( t ,a n g l e ) b k ( t ,l e n g t h * n ) ' '

Exercise4 TheKochcurveisafractalthatlookssomethinglikethis: <IMGSRC="[Link]"> TodrawaKochcurvewithlength'x',allyouhavetodois DrawaKochcurvewithlength'x/3'. Turnleft60degrees. DrawaKochcurvewithlength'x/3'. Turnright120degrees. DrawaKochcurvewithlength'x/3'. Turnleft60degrees. DrawaKochcurvewithlength'x/3'.
[Link]/wiki/Think_Python/Print_version 58/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Theonlyexceptionisif'x'[Link], 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 '. [Link] '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,[Link],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 )

Allofthefunctionswehavewrittensofararevoidtheyprintsomethingormoveturtlesaround,buttheirreturnvalueis N o n e . Inthischapter,weare(finally)[Link] a r e a ,whichreturnstheareaofacirclewiththegivenradius:


d e fa r e a ( r a d i u s ) : t e m p=m a t h . p i*r a d i u s * * 2 r e t u r nt e m p

Wehaveseenthe r e t u r n statementbefore,butinafruitfulfunctionthe r e t u r n [Link]:Returnimmediately [Link],sowecouldhavewrittenthisfunction moreconcisely:


d e fa r e a ( r a d i u s ) :
[Link]/wiki/Think_Python/Print_version 59/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

r e t u r nm a t h . p i*r a d i u s * * 2

Ontheotherhand, temporaryvariableslike t e m p oftenmakedebuggingeasier. Sometimesitisusefultohavemultiplereturnstatements,oneineachbranchofaconditional:


d e fa b s o l u t e _ v a l u e ( x ) : i fx<0 : r e t u r nx e l s e : r e t u r nx

Sincethese r e t u r n statementsareinanalternativeconditional,onlyonewillbeexecuted. Assoonasareturnstatementexecutes,[Link] r e t u r n statement,or anyotherplacetheflowofexecutioncanneverreach,iscalled deadcode. Inafruitfulfunction,itisagoodideatoensurethateverypossiblepaththroughtheprogramhitsa r e t u r n [Link]:


d e fa b s o l u t e _ v a l u e ( x ) : i fx<0 : r e t u r nx i fx>0 : r e t u r nx

Thisfunctionisincorrectbecauseif x happenstobe0,neitherconditionistrue,andthefunctionendswithouthittinga r e t u r n [Link] executiongetstotheendofafunction,thereturnvalueis N o n e ,whichisnottheabsolutevalueof0.


> > >p r i n ta b s o l u t e _ v a l u e ( 0 ) N o n e

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.

[Link]/wiki/Think_Python/Print_version

Todealwithincreasinglycomplexprograms,youmightwanttotryaprocesscalled [Link]

60/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Todealwithincreasinglycomplexprograms,youmightwanttotryaprocesscalled [Link] avoidlongdebuggingsessionsbyaddingandtestingonlyasmallamountofcodeatatime. Asanexample,supposeyouwanttofindthedistancebetweentwopoints,givenbythecoordinates(x1, y1)and(x2, y2).BythePythagoreantheorem,the distanceis:

Thefirststepistoconsiderwhata d i s t a n c e [Link],whataretheinputs(parameters)andwhatistheoutput(return value)? Inthiscase,theinputsaretwopoints,[Link],whichisafloatingpointvalue. Alreadyyoucanwriteanoutlineofthefunction:


d e fd i s t a n c e ( x 1 ,y 1 ,x 2 ,y 2 ) : r e t u r n0 . 0

Obviously,thisversiondoesn'[Link],anditruns,whichmeansthatyoucantestitbeforeyou makeitmorecomplicated. Totestthenewfunction,callitwithsamplearguments:


> > >d i s t a n c e ( 1 ,2 ,4 ,6 ) 0 . 0

Ichosethesevaluessothatthehorizontaldistanceis3andtheverticaldistanceis4thatway,theresultis5(thehypotenuseofa345triangle).When testingafunction,itisusefultoknowtherightanswer. Atthispointwehaveconfirmedthatthefunctionissyntacticallycorrect,[Link] differences x2 x1and y2 [Link].


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 p r i n t' d xi s ' ,d x p r i n t' d yi s ' ,d y r e t u r n0 . 0

Ifthefunctionisworking,itshoulddisplay ' d xi s3 ' and d yi s4 .Ifso,weknowthatthefunctionisgettingtherightargumentsandperformingthefirst [Link],thereareonlyafewlinestocheck. Nextwecomputethesumofsquaresof d x and d y :


[Link]/wiki/Think_Python/Print_version 61/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 p r i n t' d s q u a r e di s :' ,d s q u a r e d r e t u r n0 . 0

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,[Link],youmightwanttoprintthevalueof r e s u l t beforethereturnstatement. [Link] p r i n t statementswewroteareusefulfordebugging,butonce yougetthefunctionworking,[Link] scaffoldingbecauseitishelpfulforbuildingtheprogrambutisnotpartofthe finalproduct. Whenyoustartout,[Link],youmightfindyourselfwritinganddebuggingbigger [Link],incrementaldevelopmentcansaveyoualotofdebuggingtime. Thekeyaspectsoftheprocessare: [Link],ifthereisanerror,youshouldhaveagoodideawhereitis. Usetemporaryvariablestoholdintermediatevaluessoyoucandisplayandcheckthem. Oncetheprogramisworking,youmightwanttoremovesomeofthescaffoldingorconsolidatemultiplestatementsintocompoundexpressions,but onlyifitdoesnotmaketheprogramdifficulttoread.

Exercise2
Useincrementaldevelopmenttowriteafunctioncalled'h y p o t e n u s e 'thatreturnsthelengthofthehypotenuseofarighttrianglegiventhelengthsofthetwolegs [Link].

Composition
Asyoushouldexpectbynow,[Link] composition. Asanexample,wellwriteafunctionthattakestwopoints,thecenterofthecircleandapointontheperimeter,andcomputestheareaofthecircle. Assumethatthecenterpointisstoredinthevariables x c and y c ,andtheperimeterpointisin x p and y p .Thefirststepistofindtheradiusofthecircle,whichis [Link]/wiki/Think_Python/Print_version 62/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Assumethatthecenterpointisstoredinthevariables x c and y c ,andtheperimeterpointisin x p and y p .Thefirststepistofindtheradiusofthecircle,whichis [Link], d i s t a n c e ,thatdoesthat:


r a d i u s=d i s t a n c e ( x c ,y c ,x p ,y p )

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

Thetemporaryvariables r a d i u s and r e s u l t areusefulfordevelopmentanddebugging,butoncetheprogramisworking,wecanmakeitmoreconciseby composingthefunctioncalls:


d e fc i r c l e _ a r e a ( x c ,y c ,x p ,y p ) : r e t u r na r e a ( d i s t a n c e ( x c ,y c ,x p ,y p ) )

Booleanfunctions
Functionscanreturnbooleans,[Link]:
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

Itiscommontogivebooleanfunctionsnamesthatsoundlikeyes/noquestions i s _ d i v i s i b l e returnseither T r u e or F a l s e toindicatewhether x isdivisibleby y . Hereisanexample:


> > > i s _ d i v i s i b l e ( 6 ,4 ) F a l s e > > > i s _ d i v i s i b l e ( 6 ,3 ) T r u e
[Link]/wiki/Think_Python/Print_version 63/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 '

Buttheextracomparisonisunnecessary. Exercise3 Writeafunction i s _ b e t w e e n ( x ,y ,z ) thatreturns'T r u e 'if'x y z'or'F a l s e 'otherwise.

Morerecursion
WehaveonlycoveredasmallsubsetofPython,butyoumightbeinterestedtoknowthatthissubsetisa completeprogramminglanguage,whichmeansthat [Link] learnedsofar(actually,youwouldneedafewcommandstocontroldeviceslikethekeyboard,mouse,disks,etc.,butthatsall). ProvingthatclaimisanontrivialexercisefirstaccomplishedbyAlanTuring,oneofthefirstcomputerscientists(somewouldarguethathewasa mathematician,butalotofearlycomputerscientistsstartedasmathematicians).Accordingly,[Link](and accurate)discussionoftheTuringThesis,IrecommendMichaelSipsersbook IntroductiontotheTheoryofComputation. Togiveyouanideaofwhatyoucandowiththetoolsyouhavelearnedsofar,[Link] definitionissimilartoacirculardefinition,[Link] useful: frabjuous: Anadjectiveusedtodescribesomethingthatisfrabjuous. Ifyousawthatdefinitioninthedictionary,[Link],ifyoulookedupthedefinitionofthefactorialfunction,denotedwiththe symbol!,youmightgetsomethinglikethis:
[Link]/wiki/Think_Python/Print_version 64/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

0!=1 n!= n(n1)! Thisdefinitionsaysthatthefactorialof0is1,andthefactorialofanyothervalue, n,is nmultipliedbythefactorialof n1. So3!is3times2!,whichis2times1!,whichis1times0!.Puttingitalltogether,3!equals3times2times1times1,whichis6. Ifyoucanwritearecursivedefinitionofsomething,[Link] [Link] 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

Theflowofexecutionforthisprogramissimilartotheflowof c o u n t d o w n [Link] f a c t o r i a l withthevalue3: Since3isnot0,wetakethesecondbranchandcalculatethefactorialof n 1 ... Since2isnot0,wetakethesecondbranchandcalculatethefactorialof


n 1 ...

Since1isnot0,wetakethesecondbranchandcalculatethefactorial of n 1 ... Since0 is0,wetakethefirstbranchandreturn1withoutmakinganymorerecursivecalls.


[Link]/wiki/Think_Python/Print_version 65/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thereturnvalue(1)ismultipliedby n,whichis1,andtheresultisreturned. Thereturnvalue(1)ismultipliedby n,whichis2,andtheresultisreturned. Thereturnvalue(2)ismultipliedby n,whichis3,andtheresult,6,becomesthereturnvalueofthefunctioncallthatstartedthewholeprocess. Hereiswhatthestackdiagramlookslikeforthissequenceoffunctioncalls:

<IMGSRC="[Link]">

[Link],thereturnvalueisthevalueof r e s u l t ,whichistheproductof n and r e c u r s e . Inthelastframe,thelocalvariables r e c u r s e and r e s u l t donotexist,becausethebranchthatcreatesthemdoesnotexecute.

Leapoffaith
Followingtheflowofexecutionisonewaytoreadprograms,[Link] cometoafunctioncall,insteadoffollowingtheflowofexecution,you assumethatthefunctionworkscorrectlyandreturnstherightresult. Infact,[Link] m a t h . c o s or m a t h . e x p ,youdontexaminethebodiesofthose [Link]. [Link],inSection6.4,wewroteafunctioncalled i s _ d i v i s i b l e thatdetermineswhetherone [Link] withoutlookingatthebodyagain. [Link],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
[Link]/wiki/Think_Python/Print_version 66/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

fibonacci(1)=1 fibonacci(n)= fibonacci(n1)+ fibonacci(n2) TranslatedintoPython,itlookslikethis:


d e ff i b o n a c c i( n ) : i fn= =0 : r e t u r n0 e l i f n= =1 : r e t u r n1 e l s e : r e t u r nf i b o n a c c i ( n 1 )+f i b o n a c c i ( n 2 )

Ifyoutrytofollowtheflowofexecutionhere,evenforfairlysmallvaluesof n,[Link],ifyouassumethatthe tworecursivecallsworkcorrectly,thenitisclearthatyougettherightresultbyaddingthemtogether.

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

[Link]?Thereisabasecasewhen n= =0 .Butif n isnotaninteger,wecan missthebasecaseandrecurse forever. Inthefirstrecursivecall,thevalueof n [Link],[Link],itgetssmaller(morenegative),butitwillneverbe0. [Link] f a c t o r i a l functiontoworkwithfloatingpointnumbers,orwecanmake f a c t o r i a l checkthetypeofits [Link][4][Link]. Wecanusethebuiltinfunction i s i n s t a n c e [Link],wecanalsomakesuretheargumentispositive:

d e ff a c t o r i a l( n ) : i fn o ti s i n s t a n c e ( n ,i n t ) : p r i n t' F a c t o r i a li so n l yd e f i n e df o ri n t e g e r s . ' r e t u r nN o n e e l i fn<0 : p r i n t' F a c t o r i a li so n l yd e f i n e df o rp o s i t i v ei n t e g e r s . ' r e t u r nN o n e


[Link]/wiki/Think_Python/Print_version 67/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

[Link],theprogramprintsanerrormessageandreturns N o n e toindicate thatsomethingwentwrong:


> > >f a c t o r i a l ( ' f r e d ' ) F a c t o r i a li so n l yd e f i n e df o ri n t e g e r s . N o n e > > >f a c t o r i a l ( 2 ) F a c t o r i a li so n l yd e f i n e df o rp o s i t i v ei n t e g e r s . N o n e

Ifwegetpastbothchecks,thenweknowthat nisapositiveinteger,andwecanprovethattherecursionterminates. Thisprogramdemonstratesapatternsometimescalleda [Link],protectingthecodethatfollowsfromvalues [Link].

Debugging
[Link],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 [Link],[Link] callingthefunctionwithvaluesthatmakeiteasytochecktheresult(asinSection6.2). Ifthefunctionseemstobeworking,lookatthefunctioncalltomakesurethereturnvalueisbeingusedcorrectly(orusedatall!). [Link],hereisaversionof f a c t o r i a l68/282 [Link]/wiki/Think_Python/Print_version

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],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 [Link] 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,[Link],butalittlebitof scaffoldingcansavealotofdebugging.

Glossary
temporaryvariable: Avariableusedtostoreanintermediatevalueinacomplexcalculation. deadcode: Partofaprogramthatcanneverbeexecuted,oftenbecauseitappearsaftera r e t u r n statement. 'N o n e ': Aspecialvaluereturnedbyfunctionsthathavenoreturnstatementorareturnstatementwithoutanargument. incrementaldevelopment: Aprogramdevelopmentplanintendedtoavoiddebuggingbyaddingandtestingonlyasmallamountofcodeatatime.
[Link]/wiki/Think_Python/Print_version 69/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

scaffolding: Codethatisusedduringprogramdevelopmentbutisnotpartofthefinalversion. guardian: Aprogrammingpatternthatusesaconditionalstatementtocheckforandhandlecircumstancesthatmightcauseanerror.

Exercises
Exercise4
[Link]?
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
[Link]/wiki/Think_Python/Print_version 70/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Astringisasequence
Astringisa [Link]:
> > >f r u i t=' b a n a n a ' > > >l e t t e r=f r u i t [ 1 ]

Thesecondstatementselectscharacternumber1from f r u i t andassignsitto l e t t e r . Theexpressioninbracketsiscalledan [Link](hencethename). Butyoumightnotgetwhatyouexpect:


> > >p r i n tl e t t e r a

Formostpeople,thefirstletterof ' b a n a n a ' is b ,not a .Butforcomputerscientists,theindexisanoffsetfromthebeginningofthestring,andtheoffsetofthe firstletteriszero.


> > >l e t t e r=f r u i t [ 0 ] > > >p r i n tl e t t e r b

So b isthe0thletter(zeroeth)of ' b a n a n a ' , a isthe1thletter(oneeth),and n isthe2th(twoeth)letter. Youcanuseanyexpression,includingvariablesandoperators,asanindex,[Link]:


> > >l e t t e r=f r u i t [ 1 . 5 ] T y p e E r r o r :s t r i n gi n d i c e sm u s tb ei n t e g e r s

l e n
l e n isabuiltinfunctionthatreturnsthenumberofcharactersinastring:

> > >f r u i t=' b a n a n a ' > > >l e n ( f r u i t ) 6

Togetthelastletterofastring,youmightbetemptedtotrysomethinglikethis:
[Link]/wiki/Think_Python/Print_version 71/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >l e n g t h=l e n ( f r u i t ) > > >l a s t=f r u i t [ l e n g t h ] 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

Thereasonforthe I n d e x E r r o r isthatthereisnoletterin b a n a n a [Link],[Link] thelastcharacter,youhavetosubtract1from l e n g t h :


> > >l a s t=f r u i t [ l e n g t h 1 ] > > >p r i n tl a s t a

Alternatively,youcanusenegativeindices,[Link] f r u i t [ 1 ] yieldsthelastletter, f r u i t [ 2 ] yieldsthe secondtolast,andsoon.

Traversalwithaf o r loop
[Link],selecteachcharacterinturn,dosomethingtoit, [Link] 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

[Link] i n d e x<l e n ( f r u i t ) ,sowhen i n d e x isequaltothelengthofthe string,theconditionisfalse,[Link] 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.
[Link]/wiki/Think_Python/Print_version 72/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thefollowingexampleshowshowtouseconcatenation(stringaddition)anda f o r looptogenerateanabecedarianseries(thatis,inalphabeticalorder).In RobertMcCloskeysbookMakeWayforDucklings,thenamesoftheducklingsareJack,Kack,Lack,Mack,Nack,Ouack,Pack,[Link] thesenamesinorder:


p r e f i x e s=' J K L M N O P Q ' s u f f i x=' a c k ' f o rl e t t e ri np r e f i x e s : p r i n tl e t t e r+s u f f i x

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 [Link]:
> > >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

Theoperator [ n : m ] returnsthepartofthestringfromthenethcharactertothemethcharacter,[Link] counterintuitive,butitmighthelptoimaginetheindicespointing betweenthecharacters,asinthefollowingdiagram: <IMGSRC="[Link]"> Ifyouomitthefirstindex(beforethecolon),[Link],theslicegoestotheendofthestring:


[Link]/wiki/Think_Python/Print_version 73/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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,[Link]:
> > >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

[Link],an objectisthesamethingasavalue,butwewillrefinethat [Link] itemisoneofthevaluesinasequence. Thereasonfortheerroristhatstringsare immutable,[Link] variationontheoriginal:


> > >g r e e t i n g=' H e l l o ,w o r l d ! ' > > >n e w _ g r e e t i n g=' J '+g r e e t i n g [ 1 : ] > > >p r i n tn e w _ g r e e t i n g J e l l o ,w o r l d !

Thisexampleconcatenatesanewfirstletterontoasliceof g r e e t i n g .Ithasnoeffectontheoriginalstring.

Searching
[Link]/wiki/Think_Python/Print_version 74/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 [ ] [Link],ittakesacharacterandfindsthe [Link],thefunctionreturns 1 . Thisisthefirstexamplewehaveseenofa r e t u r n [Link] 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

Thisprogramdemonstratesanotherpatternofcomputationcalleda [Link] c o u n t isinitializedto0andthenincrementedeachtimean a is [Link], c o u n t containstheresultthetotalnumberof a s. Exercise5 Encapsulatethiscodeinafunctionnamed'c o u n t ',andgeneralizeitsothatitacceptsthestringandtheletterasarguments. Exercise6

[Link]/wiki/Think_Python/Print_version

75/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Rewritethisfunctionsothatinsteadoftraversingthestring,itusesthethreeparameterversionof'f i n d 'fromtheprevioussection.

s t r i n g methods
A [Link],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

Thisformofdotnotationspecifiesthenameofthemethod, u p p e r ,andthenameofthestringtoapplythemethodto, w o r d .Theemptyparenthesesindicate thatthismethodtakesnoargument. Amethodcalliscalledan invocationinthiscase,wewouldsaythatweareinvoking u p p e r onthe w o r d . Asitturnsout,thereisastringmethodnamed f i n d thatisremarkablysimilartothefunctionwewrote:


> > >w o r d=' b a n a n a ' > > >i n d e x=w o r d . f i n d ( ' a ' ) > > >p r i n ti n d e x 1

Inthisexample,weinvoke f i n d on w o r d andpasstheletterwearelookingforasaparameter. Actually,the f i n d methodismoregeneralthanourfunctionitcanfindsubstrings,notjustcharacters:


> > >w o r d . f i n d ( ' n a ' ) 2

Itcantakeasasecondargumenttheindexwhereitshouldstart:

> > >w o r d . f i n d ( ' n a ' ,3 )


[Link]/wiki/Think_Python/Print_version 76/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Andasathirdargumenttheindexwhereitshouldstop:
> > >n a m e=' b o b ' > > >n a m e . f i n d ( ' b ' ,1 ,2 ) 1

Thissearchfailsbecause b doesnotappearintheindexrangefrom 1 to 2 (notincluding 2 ). Exercise7 ' Thereisastringmethodcalled'c o u n t '[Link] thatcountsthenumberof'a 'sin b a n a n a .

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

Withwellchosenvariablenames,[Link],for(each)letterin(thefirst)word,if(the)letter(appears)in (thesecond)word,print(the)letter. Hereswhatyougetifyoucompareapplesandoranges:


> > >i n _ b o t h ( ' a p p l e s ' ,' o r a n g e s ' ) a e
[Link]/wiki/Think_Python/Print_version 77/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Stringcomparison
[Link]:
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 . '

[Link],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,[Link] incaseyouhavetodefendyourselfagainstamanarmedwithaPineapple.

Debugging
Whenyouuseindicestotraversethevaluesinasequence,[Link] 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
[Link]/wiki/Think_Python/Print_version 78/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

r e t u r nT r u e

Thefirst i f [Link],wecanreturn F a l s e immediatelyandthen,fortherestofthefunction,wecan assumethatthewordsarethesamelength.ThisisanexampleoftheguardianpatterninSection6.8.


i and j areindices: i traverses w o r d 1 forwardwhile j traverses w o r d 2 [Link],wecanreturn F a l s e [Link]

throughthewholeloopandallthelettersmatch,wereturn T r u e . Ifwetestthisfunctionwiththewordspotsandstop,weexpectthereturnvalue T r u e ,butwegetanIndexError:

> > >i s _ r e v e r s e ( ' p o t s ' ,' s t o p ' ) . . . F i l e" r e v e r s e . p y " ,l i n e1 5 ,i ni s _ r e v e r s e i fw o r d 1 [ i ]! =w o r d 2 [ j ] : 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

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

Thefirsttimethroughtheloop,thevalueof j is4,whichisoutofrangeforthestring ' p o t s ' .Theindexofthelastcharacteris3,sotheinitialvaluefor j should be l e n ( w o r d 2 ) 1 .

IfIfixthaterrorandruntheprogramagain,Iget:
[Link]/wiki/Think_Python/Print_version 79/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >i s _ r e v e r s e ( ' p o t s ' ,' s t o p ' ) 03 12 21 T r u e

Thistimewegettherightanswer,butitlookslikethelooponlyranthreetimes,[Link],itisusefulto [Link],theframefor i s _ r e v e r s e lookslikethis:

<IMGSRC="[Link]"> Itookalittlelicensebyarrangingthevariablesintheframeandaddingdottedlinestoshowthatthevaluesof i and j indicatecharactersin w o r d 1 and w o r d 2 . Exercise8 'Startingwiththisdiagram,executetheprogramonpaper,changingthevaluesof'i 'and'j '[Link].

Glossary
object: [Link],youcanuseobjectandvalueinterchangeably. sequence: Anorderedsetthatis,asetofvalueswhereeachvalueisidentifiedbyanintegerindex. item: Oneofthevaluesinasequence. index: Anintegervalueusedtoselectaniteminasequence,suchasacharacterinastring. slice: Apartofastringspecifiedbyarangeofindices. emptystring: Astringwithnocharactersandlength0,representedbytwoquotationmarks. immutable: Thepropertyofasequencewhoseitemscannotbeassigned. traverse: Toiteratethroughtheitemsinasequence,performingasimilaroperationoneach. search: Apatternoftraversalthatstopswhenitfindswhatitislookingfor.
[Link]/wiki/Think_Python/Print_version 80/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

counter: Avariableusedtocountsomething,usuallyinitializedtozeroandthenincremented. method: Afunctionthatisassociatedwithanobjectandcalledusingdotnotation. invocation: Astatementthatcallsamethod.

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 ' ' '

Astepsizeof1goesthroughthewordbackwards,sotheslice [ : : 1 ] generatesareversedstring. Usethisidiomtowriteaonelineversionof i s _ p a l i n d r o m e fromExercise'6.6'.

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 ] ] ) ,[Link]'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 [Link],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
[Link]/wiki/Think_Python/Print_version 81/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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. [Link],findanddecodesomeofthem.

Notes
1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.
[Link]/wiki/Think_Python/Print_version 82/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Casestudy:wordplay
Readingwordlists
[Link],buttheonemostsuitableforourpurposeis oneofthewordlistscollectedandcontributedtothepublicdomainbyGradyWardaspartoftheMobylexiconproject [8].Itisalistof113,809official crosswordsthatis,[Link],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 [Link] ' r ' indicatesthatthisfileisopenforreading(asopposedto ' w ' forwriting).

Thefileobjectprovidesseveralmethodsforreading,including r e a d l i n e ,whichreadscharactersfromthefileuntilitgetstoanewlineandreturnstheresultasa string:


> > >f i n . r e a d l i n e ( ) ' a a \ r \ n '

Thefirstwordinthisparticularlistisaa,[Link] \ r \ n representstwowhitespacecharacters,acarriagereturnandanewline, thatseparatethiswordfromthenext. Thefileobjectkeepstrackofwhereitisinthefile,soifyoucall r e a d l i n e again,yougetthenextword:


> > >f i n . r e a d l i n e ( ) ' a a h \ r \ n '

Thenextwordisaah,whichisaperfectlylegitimateword,[Link],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

[Link]/wiki/Think_Python/Print_version

83/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Youcanalsouseafileobjectaspartofa f o r [Link] w o r d s . t x t andprintseachword,oneperline:


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 ( ) p r i n tw o r d

Exercise1 Writeaprogramthatreads'w o r d s . t x t 'andprintsonlythewordswithmorethan20characters(notcountingwhitespace).

Exercises
[Link]. Exercise2 In1939ErnestVincentWrightpublisheda50,000wordnovelcalled [Link] English,thatsnoteasytodo. Infact,[Link],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. [Link] combinationof5forbiddenlettersthatexcludesthesmallestnumberofwords? Exercise4 Writeafunctionnamed u s e s _ o n l y thattakesawordandastringofletters,andthatreturns'T r u e '[Link] 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
[Link]/wiki/Think_Python/Print_version 84/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Writeafunctioncalled i s _ a b e c e d a r i a n thatreturns'T r u e 'ifthelettersinawordappearinalphabeticalorder(doublelettersareok).Howmanyabecedarianwords arethere?

Search
[Link] 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

The f o r looptraversesthecharactersin w o r d .Ifwefindthelettere,wecanimmediatelyreturn F a l s e [Link] loopnormally,thatmeanswedidntfindane,sowereturn T r u e . Youcanwritethisfunctionmoreconciselyusingthe i n operator,butIstartedwiththisversionbecauseitdemonstratesthelogicofthesearchpattern.


a v o i d s isamoregeneralversionof h a s _ n o _ e butithasthesamestructure:

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

Insteadofalistofforbiddenwords,[Link] w o r d thatisnotin a v a i l a b l e ,wecanreturn F a l s e .

[Link]/wiki/Think_Python/Print_version

85/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

Insteadoftraversingthelettersin w o r d ,[Link],wecanreturn F a l s e . Ifyouwerereallythinkinglikeacomputerscientist,youwouldhaverecognizedthat u s e s _ a l l wasaninstanceofapreviouslysolvedproblem,andyouwould havewritten:


d e fu s e s _ a l l ( w o r d ,r e q u i r e d ) : r e t u r nu s e s _ o n l y ( r e q u i r e d ,w o r d )

Thisisanexampleofaprogramdevelopmentmethodcalled problemrecognition,whichmeansthatyourecognizetheproblemyouareworkingonasan instanceofapreviouslysolvedproblem,andapplyapreviouslydevelopedsolution.

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 ] :
[Link]/wiki/Think_Python/Print_version 86/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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,[Link],consideranexample like ' f l o s s y ' .Thelengthofthewordis6,sothelasttimethelooprunsiswhen i is4,[Link],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 )

[Link]/wiki/Think_Python/Print_version

87/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

AssumingyoudidExercise8.8.

Debugging
[Link],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,[Link],youshouldtestwordswithaneatthebeginning,theend,and [Link],shortwords,andveryshortwords,[Link] 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![Link]

Glossary
fileobject: Avaluethatrepresentsanopenfile. problemrecognition: Awayofsolvingaproblembyexpressingitasaninstanceofapreviouslysolvedproblem. specialcase: Atestcasethatisatypicalornonobvious(andlesslikelytobehandledcorrectly).

Exercises
Exercise7
ThisquestionisbasedonaPuzzlerthatwasbroadcastontheradioprogram CarTalk[9]: Givemeawordwiththreeconsecutivedoubleletters.I'llgiveyoua

coupleofwordsthatalmostqualify,butdon'[Link],thewordcommittee,[Link] [Link]/wiki/Think_Python/Print_version

88/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

coupleofwordsthatalmostqualify,butdon'[Link],thewordcommittee,[Link] [Link]:[Link] [Link] theword? [Link] '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 '.

Exercise8
Heresanother CarTalkPuzzler[10]: [Link],itshowssixdigits,inwholemilesonly. So,ifmycarhad300,000miles,forexample,Idsee300000. Now,whatIsawthatdaywasveryinteresting.Inoticedthatthelast4digits werepalindromicthatis,[Link],5445isapalindrome,somyodometercouldhaveread31 5445. Onemilelater,[Link],it [Link],themiddle4outof6 [Link]?Onemilelater,all6werepalindromic! Thequestionis,whatwasontheodometerwhenIfirstlooked? [Link] '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]: [Link],if shes73,[Link] ananswer. [Link] wouldhappenagaininafewyears,[Link],itwouldhavehappened8 [Link],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
[Link]/wiki/Think_Python/Print_version 89/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Alistisasequence
Likeastring,a [Link],thevaluesarecharactersinalist,[Link] 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 ' ]

[Link] containsastring,afloat,aninteger,and(lo!)anotherlist:
[ ' s p a m ' ,2 . 0 ,5 ,[ 1 0 ,2 0 ] ]

Alistwithinanotherlistis nested. Alistthatcontainsnoelementsiscalledanemptylistyoucancreateonewithemptybrackets, [ ] . Asyoumightexpect,youcanassignlistvaluestovariables:


> > >c h e e s e s=[ ' C h e d d a r ' ,' E d a m ' ,' G o u d a ' ] > > >n u m b e r s=[ 1 7 ,1 2 3 ] > > >e m p t y=[ ] > > >p r i n tc h e e s e s ,n u m b e r s ,e m p t y [ ' C h e d d a r ' ,' E d a m ' ,' G o u d a ' ][ 1 7 ,1 2 3 ][ ]

Listsaremutable
[Link] bracketsspecifiestheindex.Rememberthattheindicesstartat0:
> > >p r i n tc h e e s e s [ 0 ] C h e d d a r

Unlikestrings,[Link],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
[Link]/wiki/Think_Python/Print_version 90/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[ 1 7 ,5 ]

Theoneethelementof n u m b e r s ,whichusedtobe123,isnow5. [Link] [Link] isastatediagramshowing c h e e s e s , n u m b e r s and e m p t y : <IMGSRC="[Link]"> 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 [Link]:
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

[Link],[Link] thatistocombinethefunctions r a n g e and l e n :


f o rii nr a n g e ( l e n ( n u m b e r s ) ) : n u m b e r s [ i ]=n u m b e r s [ i ]*2

Thislooptraversesthelistandupdateseachelement. l e n returnsthenumberofelementsinthelist. r a n g e returnsalistofindicesfrom0to n1,where nisthe [Link]/wiki/Think_Python/Print_version 91/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thislooptraversesthelistandupdateseachelement. l e n returnsthenumberofelementsinthelist. r a n g e returnsalistofindicesfrom0to n1,where nisthe [Link] i [Link] 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,[Link]:
[ ' 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 ]

Thefirstexamplerepeats [ 0 ] [Link] [ 1 ,2 ,3 ] threetimes.

Listslices
Thesliceoperatoralsoworksonlists:
> > >t=[ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ,' f ' ] > > >t [ 1 : 3 ] [ ' b ' ,' c ' ] > > >t [ : 4 ]
[Link]/wiki/Think_Python/Print_version 92/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[ ' a ' ,' b ' ,' c ' ,' d ' ] > > >t [ 3 : ] [ ' d ' ,' e ' ,' f ' ]

Ifyouomitthefirstindex,[Link],[Link],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
[Link], 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 ' ]
[Link]/wiki/Think_Python/Print_version 93/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >t . s o r t ( ) > > >p r i n tt [ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ]

Listmethodsareallvoidtheymodifythelistandreturn N o n e .Ifyouaccidentallywrite t=t . s o r t ( ) ,youwillbedisappointedwiththeresult.

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 [Link], x [Link] + = operatorprovidesashortwaytoupdateavariable:

t o t a l+ =x

isequivalentto:
t o t a l=t o t a l+x

Astheloopexecutes, t o t a l accumulatesthesumoftheelementsavariableusedthiswayissometimescalledan accumulator. AddinguptheelementsofalistissuchacommonoperationthatPythonprovidesitasabuiltinfunction, s u m :


> > >t=[ 1 ,2 ,3 ] > > >s u m ( t ) 6

Anoperationlikethisthatcombinesasequenceofelementsintoasinglevalueissometimescalled reduce. [Link],thefollowingfunctiontakesalistofstringsandreturnsanewlistthatcontains capitalizedstrings:


d e fc a p i t a l i z e _ a l l ( t ) : r e s=[ ] f o rsi nt : r e s . a p p e n d ( s . c a p i t a l i z e ( ) )
[Link]/wiki/Think_Python/Print_version 94/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

r e t u r nr e s
r e s isinitializedwithanemptylisteachtimethroughtheloop,[Link] r e s isanotherkindofaccumulator.

Anoperationlike c a p i t a l i z e _ a l l issometimescalleda mapbecauseitmapsafunction(inthiscasethemethod c a p i t a l i z e )ontoeachoftheelementsina sequence. [Link],thefollowingfunctiontakesalistofstringsand returnsalistthatcontainsonlytheuppercasestrings:


d e fo n l y _ u p p e r ( t ) : r e s=[ ] f o rsi nt : i fs . i s u p p e r ( ) : r e s . a p p e n d ( s ) r e t u r nr e s
i s u p p e r isastringmethodthatreturns T r u e ifthestringcontainsonlyuppercaseletters.

Anoperationlike o n l y _ u p p e r iscalleda filterbecauseitselectssomeoftheelementsandfiltersouttheothers. Mostcommonlistoperationscanbeexpressedasacombinationofmap,[Link],Pythonprovides languagefeaturestosupportthem,includingthebuiltinfunction m a p andanoperatorcalledalistcomprehension.

Exercise1
Writeafunctionthattakesalistofnumbersandreturnsthecumulativesumthatis,anewlistwherethe'i 'thelementisthesumofthefirst'i +1'elements [Link],thecumulativesumof'[ 1 ,2 ,3 ] 'is'[ 1 ,3 ,6 ] '.

Deletingelements
[Link],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 [Link],itdeletesandreturnsthelastelement.

Ifyoudontneedtheremovedvalue,youcanusethe d e l operator:
[Link]/wiki/Think_Python/Print_version 95/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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 ' ]

Thereturnvaluefrom r e m o v e is N o n e . Toremovemorethanoneelement,youcanuse d e l withasliceindex:


> > >t=[ ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ,' f ' ] > > >d e lt [ 1 : 5 ] > > >p r i n tt [ ' a ' ,' f ' ]

Asusual,thesliceselectsalltheelementsupto,butnotincluding,thesecondindex.

Listsandstrings
Astringisasequenceofcharactersandalistisasequenceofvalues,[Link] 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 ' ]

Because l i s t isthenameofabuiltinfunction,[Link] l becauseitlookstoomuchlike 1 .SothatswhyI use t . The l i s t [Link],youcanusethe s p l i t method:


> > >s=' p i n i n gf o rt h ef j o r d s ' > > >t=s . s p l i t ( ) > > >p r i n tt
[Link]/wiki/Think_Python/Print_version 96/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[ ' p i n i n g ' ,' f o r ' ,' t h e ' ,' f j o r d s ' ]

Anoptionalargumentcalleda [Link]:
> > >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 '

Inthiscasethedelimiterisaspacecharacter,so j o i n [Link],youcanusetheemptystring, ,as adelimiter.

Objectsandvalues
Ifweexecutetheseassignmentstatements:
a=' b a n a n a ' b=' b a n a n a '

Weknowthat a and b bothrefertoastring,butwedontknowwhethertheyrefertothe [Link]: <IMGSRC="[Link]"> Inonecase, a and b [Link],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

Inthisexample,Pythononlycreatedonestringobject,andboth a and b refertoit.


[Link]/wiki/Think_Python/Print_version 97/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Butwhenyoucreatetwolists,yougettwoobjects:
> > >a=[ 1 ,2 ,3 ] > > >b=[ 1 ,2 ,3 ] > > >ai sb F a l s e

Sothestatediagramlookslikethis: <IMGSRC="[Link]"> Inthiscasewewouldsaythatthetwolistsare equivalent,becausetheyhavethesameelements,butnot identical ,[Link] twoobjectsareidentical,theyarealsoequivalent,butiftheyareequivalent,theyarenotnecessarilyidentical. Untilnow,wehavebeenusingobjectandvalueinterchangeably,[Link] a=[ 1 , 2 , 3 ] , a refers [Link],wewouldsayithasthesamevalue.

Aliasing
If a referstoanobjectandyouassign b=a ,thenbothvariablesrefertothesameobject:
> > >a=[ 1 ,2 ,3 ] > > >b=a > > >bi sa T r u e

Thestatediagramlookslikethis: <IMGSRC="[Link]"> Theassociationofavariablewithanobjectiscalleda [Link],therearetworeferencestothesameobject. Anobjectwithmorethanonereferencehasmorethanonename,sowesaythattheobjectis aliased. Ifthealiasedobjectismutable,changesmadewithonealiasaffecttheother:


> > >b [ 0 ]=1 7 > > >p r i n ta [ 1 7 ,2 ,3 ]

Althoughthisbehaviorcanbeuseful,[Link],itissafertoavoidaliasingwhenyouareworkingwithmutableobjects. Forimmutableobjectslikestrings,[Link]:
[Link]/wiki/Think_Python/Print_version 98/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

a=' b a n a n a ' b=' b a n a n a '

Italmostnevermakesadifferencewhether a and b refertothesamestringornot.

Listarguments
Whenyoupassalisttoafunction,[Link],[Link], 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 ' ]

Theparameter t andthevariable l e t t e r s [Link]: <IMGSRC="[Link]"> Sincethelistissharedbytwoframes,Idrewitbetweenthem. [Link],the a p p e n d methodmodifiesalist,butthe + operatorcreatesanewlist:


> > >t 1=[ 1 ,2 ] > > >t 2=t 1 . a p p e n d ( 3 ) > > >p r i n tt 1 [ 1 ,2 ,3 ] > > >p r i n tt 2 N o n e > > >t 3=t 1+[ 3 ] > > >p r i n tt 3 [ 1 ,2 ,3 ] > > >t 2i st 3 F a l s e

[Link]/wiki/Think_Python/Print_version

99/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],thisfunction doesnot deletetheheadofalist:


d e fb a d _ d e l e t e _ h e a d ( t ) : t=t [ 1 : ]

#W R O N G !

Thesliceoperatorcreatesanewlistandtheassignmentmakes t refertoit,butnoneofthathasanyeffectonthelistthatwaspassedasanargument. [Link], t a i l returnsallbutthefirstelementofalist:


d e ft a i l ( t ) : r e t u r nt [ 1 : ]

[Link]:
> > >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)[Link]: Dontforgetthatmostlistmethodsmodifytheargumentand return N o n e .Thisistheoppositeofthestringmethods,[Link]:
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 !

[Link]/wiki/Think_Python/Print_version

100/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Because s o r t returns N o n e ,thenextoperationyouperformwith t islikelytofail. Beforeusinglistmethodsandoperators,[Link] 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. [Link],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 + [Link]:
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 !

[Link] threearelegal,buttheydothewrongthing. Makecopiestoavoidaliasing.

Ifyouwanttouseamethodlike s o r t thatmodifiestheargument,butyouneedtokeeptheoriginallistaswell,youcanmakeacopy.
o r i g=t [ : ] t . s o r t ( )

Inthisexampleyoucouldalsousethebuiltinfunction s o r t e d ,whichreturnsanew,[Link] using s o r t e d asavariablename!

Glossary
[Link]/wiki/Think_Python/Print_version 101/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

list: Asequenceofvalues. element: Oneofthevaluesinalist(orothersequence),alsocalleditems. index: Anintegervaluethatindicatesanelementinalist. nestedlist: Alistthatisanelementofanotherlist. listtraversal: Thesequentialaccessingofeachelementinalist. mapping: [Link],alistisamappingfromindicestoelements. accumulator: Avariableusedinalooptoadduporaccumulatearesult. reduce: Aprocessingpatternthattraversesasequenceandaccumulatestheelementsintoasingleresult. map: Aprocessingpatternthattraversesasequenceandperformsanoperationoneachelement. filter: Aprocessingpatternthattraversesalistandselectstheelementsthatsatisfysomecriterion. object: [Link]. equivalent: Havingthesamevalue. identical: Beingthesameobject(whichimpliesequivalence). reference: Theassociationbetweenavariableanditsvalue. aliasing: Acircumstancewheretwovariablesrefertothesameobject. delimiter: Acharacterorstringusedtoindicatewhereastringshouldbesplit.

Exercises
Exercise3
[Link]/wiki/Think_Python/Print_version 102/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Writeafunctioncalled i s _ s o r t e d thattakesalistasaparameterandreturns'T r u e 'ifthelistissortedinascendingorderand'F a l s e '[Link] (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
[Link] 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 '[Link]. Ifthereare23studentsinyourclass,whatarethechances thattwoofyouhavethesamebirthday?[Link]: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 [Link]:theydonthavetobeinthe sameorder.

Exercise7
Writeafunctionthatreadsthefile'w o r d s . t x t '[Link],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 [Link],thenyousearch [Link].

Eitherway,youcuttheremainingsearchspaceinhalf.Ifthewordlisthas113,809words,itwilltakeabout17stepstofindthewordorconcludethatitsnot [Link]/wiki/Think_Python/Print_version 103/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Eitherway,youcuttheremainingsearchspaceinhalf.Ifthewordlisthas113,809words,itwilltakeabout17stepstofindthewordorconcludethatitsnot there. Writeafunctioncalled'b i s e c t 'thattakesasortedlist andatargetvalueandreturnstheindexofthevalueinthelist,ifitsthere,or'N o n e 'ifitsnot. Oryoucouldreadthedocumentationofthe'b i s e c t 'moduleandusethat!

Exercise9
[Link].

Exercise10
[Link],shoeandcoldinterlocktoformschooled. Writeaprogramthatfindsallpairsofwordsthatinterlock. Hint:dontenumerateallpairs! Canyoufindanywordsthatarethreewayinterlockedthatis, everythirdletterformsaword,startingfromthefirst,secondorthird?

1 Thisexerciseisinspiredbyanexampleat p u z z l e r s . o r g .

Dictionaries
A dictionaryislikealist,[Link],theindiceshavetobeintegersinadictionarytheycanbe(almost)anytype. Youcanthinkofadictionaryasamappingbetweenasetofindices(whicharecalled keys)[Link] akeyandavalueiscalleda keyvaluepairorsometimesan item. Asanexample,we'llbuildadictionarythatmapsfromEnglishtoSpanishwords,sothekeysandthevaluesareallstrings. Thefunction d i c t [Link] 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 { }

[Link]/wiki/Think_Python/Print_version

104/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thesquigglybrackets, { } ,[Link],youcanusesquarebrackets:
> > >e n g 2 s p [ ' o n e ' ]=' u n o '

Thislinecreatesanitemthatmapsfromthekey o n e tothevalue ' u n o ' .Ifweprintthedictionaryagain,weseeakeyvaluepairwithacolonbetweenthekey andvalue:


> > >p r i n te n g 2 s p { ' o n e ' :' u n o ' }

[Link],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 ' }

[Link],ifyoutypethesameexampleonyourcomputer,[Link],theorder ofitemsinadictionaryisunpredictable. [Link],youusethekeystolookupthecorresponding values:


> > >p r i n te n g 2 s p [ ' t w o ' ] ' d o s '

Thekey t w o alwaysmapstothevalue ' d o s ' sotheorderoftheitemsdoesntmatter. Ifthekeyisntinthedictionary,yougetanexception:


> > >p r i n te n g 2 s p [ ' f o u r ' ] K e y E r r o r :' f o u r '

The l e n functionworksondictionariesitreturnsthenumberofkeyvaluepairs:
> > >l e n ( e n g 2 s p )
[Link]/wiki/Think_Python/Print_version 105/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

The i n operatorworksondictionariesittellsyouwhethersomethingappearsasa keyinthedictionary(appearingasavalueisnotgoodenough).


> > >' o n e 'i ne n g 2 s p T r u e > > >' u n o 'i ne n g 2 s p F a l s e

Toseewhethersomethingappearsasavalueinadictionary,youcanusethemethod v a l u e s ,whichreturnsthevaluesasalist,andthenusethe i n operator:


> > >v a l s=e n g 2 s p . v a l u e s ( ) > > >' u n o 'i nv a l s T r u e

The i n [Link],itusesasearchalgorithm,[Link],thesearch [Link],Pythonusesanalgorithmcalleda hashtablethathasaremarkableproperty:the i n operatortakesabout [Link],butyoucanreadmoreaboutitat w i k i p e d i a . o r g / w i k i / H a s h _ t a b l e .

Exercise1
Writeafunctionthatreadsthewordsin'w o r d s . t x t '[Link]'i n ' operatorasafastwaytocheckwhetherastringisinthedictionary. IfyoudidExercise'10.8',youcancomparethespeedofthisimplementationwiththelist'i n 'operatorandthebisectionsearch.

Dictionaryasasetofcounters
[Link]: Youcouldcreate26variables,[Link],foreachcharacter,incrementthe correspondingcounter,probablyusingachainedconditional. [Link](usingthebuiltinfunction o r d ),usethenumberasan indexintothelist,andincrementtheappropriatecounter. [Link],youwouldaddan [Link]. Eachoftheseoptionsperformsthesamecomputation,buteachofthemimplementsthatcomputationinadifferentway. An [Link],anadvantageofthedictionary [Link]/wiki/Think_Python/Print_version

106/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

An [Link],anadvantageofthedictionary implementationisthatwedonthavetoknowaheadoftimewhichlettersappearinthestringandweonlyhavetomakeroomforthelettersthatdoappear. Hereiswhatthecodemightlooklike:


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 ]+ =1 r e t u r nd

Thenameofthefunctionis histogram,whichisastatisticaltermforasetofcounters(orfrequencies). [Link] f o r [Link],ifthecharacter c isnotinthe dictionary,wecreateanewitemwithkey c andtheinitialvalue1(sincewehaveseenthisletteronce).If c isalreadyinthedictionaryweincrement d [ c ] . Hereshowitworks:


> > >h=h i s t o g r a m ( ' b r o n t o s a u r u s ' ) > > >p r i n th { ' a ' :1 ,' b ' :1 ,' o ' :2 ,' n ' :1 ,' s ' :2 ,' r ' :2 ,' u ' :2 ,' t ' :1 }

Thehistogramindicatesthattheletters a and ' b ' appearonce ' o ' appearstwice,andsoon.

Exercise2
Dictionarieshaveamethodcalled'g e t '[Link],'g e t 'returnsthecorrespondingvalueotherwise [Link]:
' ' > > >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 ' '

Use'g e t 'towrite'h i s t o g r a m '[Link]'i f 'statement.

[Link]/wiki/Think_Python/Print_version

107/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Loopinganddictionaries
Ifyouuseadictionaryina f o r statement,[Link], 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,[Link],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

[Link]/wiki/Think_Python/Print_version

108/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thisfunctionisyetanotherexampleofthesearchpattern,butitusesafeaturewehaventseenbefore, r a i s e .The r a i s e statementcausesanexceptioninthis caseitcausesa V a l u e E r r o r ,whichgenerallyindicatesthatthereissomethingwrongwiththevalueofaparameter. Ifwegettotheendoftheloop,thatmeans v doesntappearinthedictionaryasavalue,soweraiseanexception. Hereisanexampleofasuccessfulreverselookup:


> > >h=h i s t o g r a m ( ' p a r r o t ' ) > > >k=r e v e r s e _ l o o k u p ( h ,2 ) > > >p r i n tk r

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

TheresultwhenyouraiseanexceptionisthesameaswhenPythonraisesone:itprintsatracebackandanerrormessage. The r a i s e [Link]:


> > >r a i s eV a l u e E r r o r ,' v a l u ed o e sn o ta p p e a ri nt h ed i c t i o n a r y ' 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? V a l u e E r r o r :v a l u ed o e sn o ta p p e a ri nt h ed i c t i o n a r y

Areverselookupismuchslowerthanaforwardlookupifyouhavetodoitoften,orifthedictionarygetsbig,theperformanceofyourprogramwillsuffer. Exercise4 Modify r e v e r s e _ l o o k u p sothatitbuildsandreturnsalistof allkeysthatmapto'v ',oranemptylistiftherearenone.

Dictionariesandlists
[Link],ifyouweregivenadictionarythatmapsfromletterstofrequencies,youmightwanttoinvertitthatis, [Link],eachvalueintheinverteddictionary shouldbealistofletters. Hereisafunctionthatinvertsadictionary:
[Link]/wiki/Think_Python/Print_version 109/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

d e fi n v e r t _ d i c t ( d ) : i n v=d i c t ( ) f o rk e yi nd : v a l=d [ k e y ] i fv a ln o ti ni n v : i n v [ v a l ]=[ k e y ] e l s e : i n v [ v a l ] . a p p e n d ( k e y ) r e t u r ni n v

Eachtimethroughtheloop, k e y getsakeyfrom d and v a l [Link] 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 ' ] }

Andhereisadiagramshowing h i s t and i n v : <IMGSRC="[Link]"> Adictionaryisrepresentedasaboxwiththetype d i c t [Link],floatsorstrings,Iusuallydrawthem insidethebox,butIusuallydrawlistsoutsidethebox,justtokeepthediagramsimple. Listscanbevaluesinadictionary,asthisexampleshows,[Link]:


> > >t=[ 1 ,2 ,3 ] > > >d=d i c t ( ) > > >d [ t ]=' o o p s ' 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? T y p e E r r o r :l i s to b j e c t sa r eu n h a s h a b l e

Imentionedearlierthatadictionaryisimplementedusingahashtableandthatmeansthatthekeyshavetobe hashable.
[Link]/wiki/Think_Python/Print_version 110/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

A hashisafunctionthattakesavalue(ofanykind)[Link],calledhashvalues,tostoreandlookupkeyvalue pairs. [Link],likelists,[Link],whenyoucreateakeyvaluepair, [Link],[Link] youmighthavetwoentriesforthesamekey,[Link],thedictionarywouldntworkcorrectly. Thatswhythekeyshavetobehashable,[Link],whichwewill seeinthenextchapter. Sincedictionariesaremutable,theycantbeusedaskeys,buttheycanbeusedasvalues.

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 [Link],theruntimeincreasesveryquickly. Tounderstandwhy,considerthis callgraphfor f i b o n a c c i with n = 4 : <IMGSRC="[Link]"> Acallgraphshowsasetoffunctionframes,[Link], 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 ) [Link],anditgetsworseastheargumentgetsbigger. [Link] 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 [Link]:0mapsto0and1mapsto1.
[Link]/wiki/Think_Python/Print_version 111/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Whenever f i b o n a c c i iscalled,itchecks k n o w n .Iftheresultisalreadythere,[Link],addittothe dictionary,andreturnit.

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 [Link],whichdisappearwhentheirfunctionends,globalvariablespersistfromone functioncalltothenext. Itiscommontouseglobalvariablesfor flagsthatis,booleanvariablesthatindicate(flag)[Link],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,[Link]:
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

Butifyourunityouwillseethatthevalueof b e e n _ c a l l e d [Link] e x a m p l e 2 createsanewlocalvariablenamed b e e n _ c a l l e d .Thelocal variablegoesawaywhenthefunctionends,andhasnoeffectontheglobalvariable. Toreassignaglobalvariableinsideafunctionyouhaveto declaretheglobalvariablebeforeyouuseit:


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 ( ) : g l o b a lb e e n _ c a l l e d b e e n _ c a l l e d=T r u e

The g l o b a l statementtellstheinterpretersomethinglike,Inthisfunction,whenIsay b e e n _ c a l l e d ,Imeantheglobalvariabledontcreatealocalone.

[Link]/wiki/Think_Python/Print_version

112/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

Pythonassumesthat c o u n t islocal,[Link],again,istodeclare c o u n t global.


d e fe x a m p l e 3 ( ) : g l o b a lc o u n t c o u n t+ =1

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 .
[Link]/wiki/Think_Python/Print_version 113/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Valueswithtype i n t havealimitedrangelongintegerscanbearbitrarilybig,butastheygetbiggertheyconsumemorespaceandtime. Themathematicaloperatorsworkonlongintegers,andthefunctionsinthe m a t h module,too,soingeneralanycodethatworkswith i n t willalsoworkwith l o n g . Anytimetheresultofacomputationistoobigtoberepresentedwithaninteger,Pythonconvertstheresultasalonginteger:


> > >1 0 0 0*1 0 0 0 1 0 0 0 0 0 0 > > >1 0 0 0 0 0*1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 L

Inthefirstcasetheresulthastype i n t inthesecondcaseitis l o n g .

Exercise7
[Link][14]andwrite functionstoencodeanddecodemessages.

Debugging
[Link] datasets: Scaledowntheinput: Ifpossible,[Link],startwithjustthefirst10lines,orwiththesmallestexample [Link],or(better)modifytheprogramsoitreadsonlythefirst n [Link],youcanreduce
n tothesmallestvaluethatmanifeststheerror,andthenincreaseitgraduallyasyoufindandcorrecterrors.

Checksummariesandtypes: Insteadofprintingandcheckingtheentiredataset,considerprintingsummariesofthedata:forexample,thenumberofitemsinadictionaryorthe [Link],itisoftenenoughto printthetypeofavalue. Writeselfchecks: [Link],ifyouarecomputingtheaverageofalistofnumbers,youcouldcheck [Link] [Link]. Prettyprinttheoutput: [Link] p p r i n t moduleprovidesa p p r i n t functionthat displaysbuiltintypesinamorehumanreadableformat. Again,timeyouspendbuildingscaffoldingcanreducethetimeyouspenddebugging.
[Link]/wiki/Think_Python/Print_version 114/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Glossary
dictionary: Amappingfromasetofkeystotheircorrespondingvalues. keyvaluepair: Therepresentationofthemappingfromakeytoavalue. item: Anothernameforakeyvaluepair. key: Anobjectthatappearsinadictionaryasthefirstpartofakeyvaluepair. value: [Link]. implementation: Awayofperformingacomputation. hashtable: ThealgorithmusedtoimplementPythondictionaries. hashfunction: Afunctionusedbyahashtabletocomputethelocationforakey. hashable: [Link],floatsandstringsarehashablemutabletypeslikelistsanddictionariesarenot. lookup: Adictionaryoperationthattakesakeyandfindsthecorrespondingvalue. reverselookup: Adictionaryoperationthattakesavalueandfindsoneormorekeysthatmaptoit. singleton: Alist(orothersequence)withasingleelement. callgraph: Adiagramthatshowseveryframecreatedduringtheexecutionofaprogram,withanarrowfromeachcallertoeachcallee. histogram: Asetofcounters. memo: Acomputedvaluestoredtoavoidunnecessaryfuturecomputation. globalvariable: [Link]. flag: Abooleanvariableusedtoindicatewhetheraconditionistrue.
[Link]/wiki/Think_Python/Print_version 115/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

declaration: Astatementlike g l o b a l thattellstheinterpretersomethingaboutavariable.

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]: [Link],fiveletterwordrecentlythathasthefollowingunique [Link],theremaininglettersformahomophoneoftheoriginalword,thatisawordthatsoundsexactlythe [Link],thatis,[Link] thequestionis,whatstheword? [Link] thefiveletterword,[Link], [Link],Iamleftwithafourletterword,[Link],Holycow,didyouseetherackon thatbuck!Itmusthavebeenaninepointer![Link],andremovether,instead,youreleftwiththe word,wack,whichisarealword,itsjustnotahomophoneoftheothertwowords. Butthereis,however,atleastonewordthatDanandweknowof, whichwillyieldtwohomophonesifyouremoveeitherofthefirsttwolettersto maketwo,[Link],whatstheword? ' YoucanusethedictionaryfromExercise'11.1'tocheckwhetherastringisinthewordlist. Tocheckwhethertwowordsarehomophones,[Link]'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
[Link]/wiki/Think_Python/Print_version 116/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

1. InPython3.0,theresultofthisdivisionisa f l o a t .Thenewoperator / / performsintegerdivision.

Tuples
Tuplesareimmutable
[Link],andtheyareindexedbyintegers,[Link] 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 ' >

Withoutthecomma,Pythontreats ( ' a ' ) asastringinparentheses:


> > >t 2=( ' a ' ) > > >t y p e ( t 2 ) < t y p e' s t r ' >

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
[Link]/wiki/Think_Python/Print_version 117/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

( ' l ' ,' u ' ,' p ' ,' i ' ,' n ' ,' s ' )

Because t u p l e isthenameofabuiltinfunction,youshouldavoidusingitasavariablename. [Link]:


> > >t=( ' a ' ,' b ' ,' c ' ,' d ' ,' e ' ) > > >p r i n tt [ 0 ] ' a '

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
[Link],[Link],toswap a and b :
> > >t e m p=a > > >a=b > > >b=t e m p

Thissolutioniscumbersome tupleassignmentismoreelegant:
> > >a ,b=b ,a

[Link]/wiki/Think_Python/Print_version

118/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link] sideareevaluatedbeforeanyoftheassignments. Thenumberofvariablesontheleftandthenumberofvaluesontherighthavetobethesame:


> > >a ,b=1 ,2 ,3 V a l u e E r r o r :t o om a n yv a l u e st ou n p a c k

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 ( ' @ ' )

Thereturnvaluefrom s p l i t isalistwithtwoelementsthefirstelementisassignedto u n a m e ,thesecondto d o m a i n .


> > >p r i n tu n a m e m o n t y > > >p r i n td o m a i n p y t h o n . o r g

Tuplesasreturnvalues
Strictlyspeaking,afunctioncanonlyreturnonevalue,butifthevalueisatuple,[Link],ifyouwant todividetwointegersandcomputethequotientandremainder,itisinefficienttocompute x / y andthen x % y .Itisbettertocomputethembothatthesame time. Thebuiltinfunction d i v m o d takestwoargumentsandreturnsatupleoftwovalues,[Link]:
> > >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

[Link]/wiki/Think_Python/Print_version

119/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link] * [Link], 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 [Link]:
> > >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

Runthisfunctionwith1,2,3and4ormoreargumentsandmakesureyouunderstandwhatitdoes. Thecomplementofgatheris [Link],youcanusethe * [Link], d i v m o d takesexactlytwoargumentsitdoesntworkwithatuple:


> > >t=( 7 ,3 ) > > >d i v m o d ( t ) T y p e E r r o r :d i v m o de x p e c t e d2a r g u m e n t s ,g o t1

Butifyouscatterthetuple,itworks:
> > >d i v m o d ( * t ) ( 2 ,1 )

[Link]/wiki/Think_Python/Print_version

120/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Exercise1
[Link],'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

[Link]/wiki/Think_Python/Print_version

121/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Eachtimethroughtheloop,Pythonselectsthenexttupleinthelistandassignstheelementsto l e t t e r and n u m b e r .Theoutputofthisloopis:


0a 1b 2c

Ifyoucombine z i p , f o r andtupleassignment,yougetausefulidiomfortraversingtwo(ormore)[Link], h a s _ m a t c h takestwo sequences, t 1 and t 2 ,andreturns T r u e ifthereisanindex i suchthat t 1 [ i ]= =t 2 [ i ] :


d e fh a s _ m a t c h ( t 1 ,t 2 ) : f o rx ,yi nz i p ( t 1 ,t 2 ) : i fx= =y : r e t u r nT r u e r e t u r nF a l s e

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:
[Link]/wiki/Think_Python/Print_version 122/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >t=[ ( ' a ' ,0 ) ,( ' c ' ,2 ) ,( ' b ' ,1 ) ] > > >d=d i c t ( t ) > > >p r i n td { ' a ' :0 ,' c ' :2 ,' b ' :1 }

Combining d i c t with z i p yieldsaconcisewaytocreateadictionary:


> > >d=d i c t ( z i p ( ' a b c ' ,r a n g e ( 3 ) ) ) > > >p r i n td { ' a ' :0 ,' c ' :2 ,' b ' :1 }

Thedictionarymethod u p d a t e alsotakesalistoftuplesandaddsthem,askeyvaluepairs,toanexistingdictionary. Combining i t e m s ,tupleassignmentand f o r ,yougettheidiomfortraversingthekeysandvaluesofadictionary:


f o rk e y ,v a li nd . i t e m s ( ) : p r i n tv a l ,k e y

Theoutputofthisloopis:
0a 2c 1b

Again. Itiscommontousetuplesaskeysindictionaries(primarilybecauseyoucantuselists).Forexample,atelephonedirectorymightmapfromlastname,first [Link] l a s t , f i r s t and n u m b e r ,wecouldwrite:


d i r e c t o r y [ l a s t , f i r s t ]=n u m b e r

[Link].
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 ]

Thislooptraversesthekeysin d i r e c t o r y ,[Link] l a s t and f i r s t ,thenprintsthenameandcorresponding telephonenumber.

[Link]/wiki/Think_Python/Print_version

123/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link] example,thetuple ( ' C l e e s e ' ,' J o h n ' ) wouldappear: <IMGSRC="[Link]"> [Link],adiagramofthetelephonedirectorymightappear: <IMGSRC="[Link]"> HerethetuplesareshownusingPythonsyntaxasagraphicalshorthand. ThetelephonenumberinthediagramisthecomplaintslinefortheBBC,sopleasedontcallit.

Comparingtuples
[Link],itgoes ontothenextelements,andsoon,[Link](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 [Link],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 )

[Link]/wiki/Think_Python/Print_version

124/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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,[Link] r e v e r s e = T r u e tells s o r t togoin

decreasingorder. Thesecondlooptraversesthelistoftuplesandbuildsalistofwordsindescendingorderoflength.

Exercise2
Inthisexample,tiesarebrokenbycomparingwords,[Link] [Link]:seethe'r a n d o m 'functioninthe'r a n d o m 'module.

Sequencesofsequences
Ihavefocusedonlistsoftuples,butalmostalloftheexamplesinthischapteralsoworkwithlistsoflists,tuplesoftuples,[Link] enumeratingthepossiblecombinations,itissometimeseasiertotalkaboutsequencesofsequences. Inmanycontexts,thedifferentkindsofsequences(strings,listsandtuples)[Link]? Tostartwiththeobvious,[Link] theabilitytochangethecharactersinastring(asopposedtocreatinganewstring),youmightwanttousealistofcharactersinstead. Listsaremorecommonthantuples,[Link]: Insomecontexts,likea r e t u r n statement,[Link],youmightpreferalist. Ifyouwanttouseasequenceasadictionarykey,youhavetouseanimmutabletypelikeatupleorstring. Ifyouarepassingasequenceasanargumenttoafunction,usingtuplesreducesthepotentialforunexpectedbehaviorduetoaliasing. Becausetuplesareimmutable,theydontprovidemethodslike s o r t and r e v e r s e ,[Link] s o r t e d and r e v e r s e d ,whichtakeanysequenceasaparameterandreturnanewlistwiththesameelementsinadifferentorder.

Debugging
Lists,dictionariesandtuplesareknowngenericallyas datastructuresinthischapterwearestartingtoseecompounddatastructures,likelistsoftuples, [Link],buttheyarepronetowhatIcall shapeerrorsthatis, errorscausedwhenadatastructurehasthewrongtype,[Link],ifyouareexpectingalistwithoneintegerandIgiveyouaplainold integer(notinalist),itwontwork.

Tohelpdebugthesekindsoferrors,Ihavewrittenamodulecalled s t r u c t s h a p e thatprovidesafunction,alsocalled s t r u c t s h a p e ,thattakesanykindofdata [Link]/wiki/Think_Python/Print_version

125/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Tohelpdebugthesekindsoferrors,Ihavewrittenamodulecalled s t r u c t s h a p e thatprovidesafunction,alsocalled s t r u c t s h a p e ,thattakesanykindofdata [Link] t h i n k p y t h o n . c o m / c o d e / s t r u c t s h a p e . p y Herestheresultforasimplelist:


> > >f r o ms t r u c t s h a p ei m p o r ts t r u c t s h a p e > > >t=[ 1 , 2 , 3 ] > > >p r i n ts t r u c t s h a p e ( t ) l i s to f3i n t

Afancierprogrammightwritelistof3int s,[Link]:
> > >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:
[Link]/wiki/Think_Python/Print_version 126/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Animmutablesequenceofelements. tupleassignment: [Link] 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 [Link] [Link]'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 ' ] ' '

Hint:[Link],howcanyou representthesetoflettersinawaythatcanbeusedasakey? Modifythepreviousprogramsothatitprintsthelargestset


[Link]/wiki/Think_Python/Print_version 127/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

ofanagramsfirst,followedbythesecondlargestset,andsoon. InScrabbleabingoiswhenyouplayallseventilesin yourrack,alongwithaletterontheboard,toformaneightletterword.Whatsetof8lettersformsthemostpossiblebingos?Hint:thereareseven. 'Twowordsformametathesispairifyoucantransformone intotheotherbyswappingtwoletters'' 3''forexample,[Link]: donttestallpairsofwords,anddonttestallpossibleswaps.''Youcandownloadasolutionfrom'''t h i n k p y t h o n . c o m / c o d e / a n a g r a m _ s e t s . p y '''.'

Exercise5
HeresanotherCarTalkPuzzler4: WhatisthelongestEnglishword,thatremainsavalidEnglishword,asyouremoveitslettersoneatatime? Now,letterscanberemovedfrom eitherend,orthemiddle,[Link],[Link] dothat,[Link] toknowwhatsthelongestwordandhowmanylettersdoesithave? Imgoingtogiveyoualittlemodestexample:[Link]?Youstart offwithsprite,youtakealetteroff,onefromtheinterioroftheword,take theraway,andwereleftwiththewordspite,thenwetaketheeofftheend,wereleftwithspit,wetakethesoff,wereleftwithpit,it,andI. Writeaprogramtofindallwordsthatcanbereducedinthisway, andthenfindthelongestone. Thisexerciseisalittlemorechallengingthanmost,soherearesomesuggestions: Youmightwanttowriteafunctionthattakesawordand [Link]. Recursively,awordisreducibleifanyofitschildren [Link],youcanconsidertheemptystringreducible. ThewordlistIprovided,'w o r d s . t x t ',doesnt [Link],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 '.
[Link]/wiki/Think_Python/Print_version 128/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

1 InPython3.0, z i p returnsaniteratoroftuples,butformostpurposes,aniteratorbehaveslikealist. 2 ThisbehaviorisslightlydifferentinPython3.0. 3 Thisexerciseisinspiredbyanexampleat p u z z l e r s . o r g . 4


w w w . c a r t a l k . c o m / c o n t e n t / p u z z l e r / t r a n s c r i p t s / 2 0 0 6 5 1

=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 [Link]:
> > >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 ! " # $ % & ' ( ) * + , . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~

Also,youmightconsiderusingthestringmethods's t r i p ', 'r e p l a c e 'and't r a n s l a t e '.

Exercise2
GotoProjectGutenberg('g u t e n b e r g . o r g ')anddownloadyourfavoriteoutofcopyrightbookinplaintextformat. Modifyyourprogramfromthepreviousexercisetoreadthebookyoudownloaded,skipovertheheaderinformationatthebeginningofthefile,andprocess therestofthewordsasbefore. Thenmodifytheprogramtocountthetotalnumberofwordsinthebook,andthenumberoftimeseachwordisused. [Link],[Link] extensivevocabulary?

[Link]/wiki/Think_Python/Print_version

129/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Exercise3
Modifytheprogramfromthepreviousexercisetoprintthe20mostfrequentlyusedwordsinthebook.

Exercise4
Modifythepreviousprogramtoreadawordlist(seeSection'9.1')[Link] typos?Howmanyofthemarecommonwordsthat shouldbeinthewordlist,andhowmanyofthemarereallyobscure?

Randomnumbers
Giventhesameinputs,mostcomputerprogramsgeneratethesameoutputseverytime,sotheyaresaidtobe [Link] thing,[Link],though,[Link] obviousexample,buttherearemore. Makingaprogramtrulynondeterministicturnsouttobenotsoeasy,[Link] algorithmsthatgenerate [Link], 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

Thefunction r a n d i n t takesparameters l o w and h i g h andreturnsanintegerbetween l o w and h i g h (includingboth).


> > >r a n d o m . r a n d i n t ( 5 ,1 0 ) 5 > > >r a n d o m . r a n d i n t ( 5 ,1 0 ) 9

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 )
[Link]/wiki/Think_Python/Print_version 130/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 [Link],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 } ' '

yourfunctionshould' a 'withprobability'2/3'and b withprobability'1/3'.

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 ' )

Thisprogramreads e m m a . t x t ,whichcontainsthetextof EmmabyJaneAusten.


p r o c e s s _ f i l e loopsthroughthelinesofthefile,passingthemoneatatimeto p r o c e s s _ l i n e .Thehistogram h isbeingusedasanaccumulator.
[Link]/wiki/Think_Python/Print_version 131/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

p r o c e s s _ l i n e usesthestringmethod r e p l a c e toreplacehyphenswithspacesbeforeusing s p l i t [Link]

anduses s t r i p and l o w e r toremovepunctuationandconverttolowercase.(Itisashorthandtosaythatstringsareconvertedrememberthatstringare immutable,somethodslike s t r i p and l o w e r returnnewstrings.) Finally, p r o c e s s _ l i n e updatesthehistogrambycreatinganewitemorincrementinganexistingone. Tocountthetotalnumberofwordsinthefile,wecanaddupthefrequenciesinthehistogram:


d e ft o t a l _ w o r d s ( h ) : r e t u r ns u m ( h . v a l u e s ( ) )

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:
[Link]/wiki/Think_Python/Print_version 132/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 : 1 0 ] : p r i n tw o r d ,' \ t ' ,f r e q

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
[Link], [Link],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

[Link] defaultvalueof n u m is10. Ifyouonlyprovideoneargument:


p r i n t _ m o s t _ c o m m o n ( h i s t )
n u m [Link]:

p r i n t _ m o s t _ c o m m o n ( h i s t ,2 0 )
n u m [Link],theoptionalargument overridesthedefaultvalue.
[Link]/wiki/Think_Python/Print_version 133/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

Tofindthewordsinthebookthatarenotin w o r d s . t x t ,wecanuse p r o c e s s _ f i l e tobuildahistogramfor w o r d s . t x t ,andthensubtract:


w o r d s=p r o c e s s _ f i l e ( ' w o r d s . t x t ' ) d i f f=s u b t r a c t ( h i s t ,w o r d s ) p r i n t" 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 : " f o rw o r di nd i f f . k e y s ( ) : p r i n tw o r d ,

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. . .

[Link],likerencontre,[Link] thelist!

Exercise6
Pythonprovidesadatastructurecalled's e t '[Link]'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
[Link]/wiki/Think_Python/Print_version 134/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Theexpression [ w o r d ]*f r e q createsalistwith f r e q copiesofthestring w o r d .The e x t e n d methodissimilarto a p p e n d exceptthattheargumentisasequence.

Exercise7
Thisalgorithmworks,butitisnotveryefficienteachtimeyouchoosearandomword,itrebuildsthelist,[Link] 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

[Link],inarealsentenceyouwouldexpect anarticlelikethetobefollowedbyanadjectiveoranoun,andprobablynotaverboradverb.

OnewaytomeasurethesekindsofrelationshipsisMarkovanalysis,whichcharacterizes,foragivensequenceofwords,theprobabilityofthewordthatcomes [Link]/wiki/Think_Python/Print_version 135/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

OnewaytomeasurethesekindsofrelationshipsisMarkovanalysis,whichcharacterizes,foragivensequenceofwords,theprobabilityofthewordthatcomes [Link],thesong Eric,theHalfaBeebegins: Halfabee,philosophically, Must,ipsofacto,halfnotbe. Buthalfthebeehasgottobe Visavis,[Link]? Butcanabeebesaidtobe Ornottobeanentirebee Whenhalfthebeeisnotabee Duetosomeancientinjury? Inthistext,thephrasehalftheisalwaysfollowedbythewordbee,butthephrasethebeemightbefollowedbyeitherhasoris. TheresultofMarkovanalysisisamappingfromeachprefix(likehalftheandthebee)toallpossiblesuffixes(likehasandis). Giventhismapping,[Link],youcancombinethe endoftheprefixandthenewsuffixtoformthenextprefix,andrepeat. Forexample,ifyoustartwiththeprefixHalfa,thenthenextwordhastobebee,[Link] bee,sothenextsuffixmightbephilosophically,beordue. Inthisexamplethelengthoftheprefixisalwaystwo,[Link] analysis.

Exercise8
Markovanalysis: [Link] [Link],tuple,[Link] lengthtwo,butyoushouldwritetheprograminawaythatmakesiteasytotryotherlengths. [Link] withprefixlength2: Hewasveryclever,beitsweetnessorbeangry,ashamedoronly amused,[Link]?""Icannotmakespeeches,Emma:"hesooncut itallhimself. Forthisexample,[Link],[Link],italmostmakessense, butnotquite. Whathappensifyouincreasetheprefixlength?Doestherandomtextmakemoresense? Onceyourprogramisworking,youmightwanttotryamashup:ifyouanalyzetextfromtwoormorebooks,therandomtextyougeneratewillblend
[Link]/wiki/Think_Python/Print_version 136/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

thevocabularyandphrasesfromthesourcesininterestingways.

Datastructures
UsingMarkovanalysistogeneraterandomtextisfun,butthereisalsoapointtothisexercise:[Link] exercises,youhadtochoose: Howtorepresenttheprefixes. Howtorepresentthecollectionofpossiblesuffixes. Howtorepresentthemappingfromeachprefixtothecollectionofpossiblesuffixes. Ok,thelastoneistheeasytheonlymappingtypewehaveseenisadictionary,soitisthenaturalchoice. Fortheprefixes,themostobviousoptionsarestring,listofstrings,[Link],oneoptionisalistanotherisahistogram(dictionary). Howshouldyouchoose?[Link],weneedtobeable [Link],ifthecurrentprefixisHalfa,andthenextwordisbee,youneedtobeabletoform thenextprefix,abee. Yourfirstchoicemightbealist,sinceitiseasytoaddandremoveelements,butwealsoneedtobeabletousetheprefixesaskeysinadictionary,sothat [Link],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. [Link] hardertodoefficiently(seeExercise13.7). Sofarwehavebeentalkingmostlyabouteaseofimplementation,[Link]. Sometimesthereisatheoreticalreasontoexpectonedatastructuretobefasterthanotherforexample,Imentionedthatthe i n operatorisfasterfor dictionariesthanforlists,atleastwhenthenumberofelementsislarge. [Link] iscalled [Link],andthenseeifitisfastenoughfortheintended [Link],[Link],therearetools,likethe p r o f i l e module,thatcanidentifytheplacesinaprogramthattakethemosttime.

[Link],usingahistogramforthecollectionofsuffixesmighttakelessspacebecauseyouonlyhaveto 137/282 [Link]/wiki/Think_Python/Print_version

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],usingahistogramforthecollectionofsuffixesmighttakelessspacebecauseyouonlyhaveto storeeachwordonce,[Link],savingspacecanalsomakeyourprogramrunfaster,andinthe extreme,[Link],spaceisasecondaryconsiderationafterruntime. Onefinalthought:inthisdiscussion,[Link] phases,[Link] savedduringgenerationexceededthetimespentinconversion.

Debugging
Whenyouaredebuggingaprogram,andespeciallyifyouareworkingonahardbug,therearefourthingstotry: reading: Examineyourcode,readitbacktoyourself,andcheckthatitsayswhatyoumeanttosay. running: [Link],theproblem becomesobvious,butsometimesyouhavetospendsometimetobuildscaffolding. ruminating: Takesometimetothink!Whatkindoferrorisit:syntax,runtime,semantic?Whatinformationcanyougetfromtheerrormessages,orfromtheoutput oftheprogram?Whatkindoferrorcouldcausetheproblemyoureseeing?Whatdidyouchangelast,beforetheproblemappeared? retreating: Atsomepoint,thebestthingtodoisbackoff,undoingrecentchanges,[Link] canstartingrebuilding. [Link]. Forexample,readingyourcodemighthelpiftheproblemisatypographicalerror,[Link] understandwhatyourprogramdoes,youcanreadit100timesandneverseetheerror,becausetheerrorisinyourhead. Runningexperimentscanhelp,especiallyifyourunsmall,[Link],youmightfallintoa patternIcallrandomwalkprogramming,[Link],random walkprogrammingcantakealongtime. [Link] ormorepossibilities,trytothinkofatestthatwouldeliminateoneofthem. [Link](orevenyourself),youwillsometimesfindtheanswer beforeyoufinishaskingthequestion. Buteventhebestdebuggingtechniqueswillfailiftherearetoomanyerrors,[Link] optionistoretreat,simplifyingtheprogramuntilyougettosomethingthatworksandthatyouunderstand.

Beginningprogrammersareoftenreluctanttoretreatbecausetheycantstandtodeletealineofcode(evenifitswrong).Ifitmakesyoufeelbetter,copy 138/282 [Link]/wiki/Think_Python/Print_version

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Beginningprogrammersareoftenreluctanttoretreatbecausetheycantstandtodeletealineofcode(evenifitswrong).Ifitmakesyoufeelbetter,copy [Link]. Findingahardbugrequiresreading,running,ruminating,[Link],trytheothers.

Glossary
deterministic: Pertainingtoaprogramthatdoesthesamethingeachtimeitruns,giventhesameinputs. pseudorandom: Pertainingtoasequenceofnumbersthatappeartoberandom,butaregeneratedbyadeterministicprogram. defaultvalue: Thevaluegiventoanoptionalparameterifnoargumentisprovided. override: Toreplaceadefaultvaluewithanargument. benchmarking: Theprocessofchoosingbetweendatastructuresbyimplementingalternativesandtestingthemonasampleofthepossibleinputs.

Exercises
Exercise9
Therankofawordisitspositioninalistofwordssortedbyfrequency:themostcommonwordhasrank1,thesecondmostcommonhasrank2,etc. [Link],itpredictsthatthefrequency,'f',oftheword withrank'r'is:

Writeafunctionnamed'a c k '[Link]'a c k ( 3 ,4 ) ',[Link] of'm 'and'n '?

Exercise6
Apalindromeisawordthatisspelledthesamebackwardandforward,[Link],awordisapalindromeifthefirstandlast lettersarethesameandthemiddleisapalindrome.
[Link]/wiki/Think_Python/Print_version 139/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 ' [Link]'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 '[Link]'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 '[Link],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.

[Link]/wiki/Think_Python/Print_version

140/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Iteration
Multipleassignment
Asyoumayhavediscovered,[Link] 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,[Link] p r i n t statementsuppressesthenewline,whichiswhybothoutputsappearonthesameline. Hereiswhat multipleassignmentlookslikeinastatediagram: <IMGSRC="[Link]"> [Link] equalsign(= )forassignment,itistemptingtointerpretastatementlike a=b [Link]! First,[Link],inmathematics,if a=7then7= [Link],thestatement a=7 islegaland 7=a isnot. Furthermore,inmathematics,astatementofequalityiseithertrueorfalse,[Link] a= bnow,then awillalwaysequal [Link],anassignment statementcanmaketwovariablesequal,buttheydonthavetostaythatway:
a=5 b=a a=3

#aa n dba r en o we q u a l #aa n dba r en ol o n g e re q u a l

Thethirdlinechangesthevalueof a butdoesnotchangethevalueof b ,sotheyarenolongerequal. Althoughmultipleassignmentisfrequentlyhelpful,[Link],itcanmakethecodedifficult toreadanddebug.

Updatingvariables
Oneofthemostcommonformsofmultipleassignmentisan update,wherethenewvalueofthevariabledependsontheold.
x=x + 1
[Link]/wiki/Think_Python/Print_version 141/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thismeansgetthecurrentvalueof x ,addone,andthenupdate x withthenewvalue. Ifyoutrytoupdateavariablethatdoesntexist,yougetanerror,becausePythonevaluatestherightsidebeforeitassignsavalueto x :


> > >x=x + 1 N a m e E r r o r :n a m e' x 'i sn o td e f i n e d

Beforeyoucanupdateavariable,youhaveto initializeit,usuallywithasimpleassignment:
> > >x=0 > > >x=x + 1

Updatingavariablebyadding1iscalledan incrementsubtracting1iscalleda decrement.

Thew h i l e statement
[Link] peopledopoorly. Wehaveseentwoprograms, c o u n t d o w n and p r i n t _ n ,thatuserecursiontoperformrepetition,whichisalsocalled [Link], [Link] f o r [Link]. Anotheristhe w h i l e [Link] 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 [Link],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.
[Link]/wiki/Think_Python/Print_version 142/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link] loopwillrepeatforever,whichiscalledan [Link] shampoo,Lather,rinse,repeat,areaninfiniteloop. Inthecaseof c o u n t d o w n ,wecanprovethattheloopterminatesbecauseweknowthatthevalueof n isfinite,andwecanseethatthevalueof n getssmaller eachtimethroughtheloop,[Link],itisnotsoeasytotell:


d e fs e q u e n c e ( n ) : w h i l en! =1 : p r i n tn , i fn % 2= =0 : n=n / 2 e l s e : n=n * 3 + 1

#ni se v e n #ni so d d

Theconditionforthisloopis n! =1 ,sotheloopwillcontinueuntil n is 1 ,whichmakestheconditionfalse. Eachtimethroughtheloop,theprogramoutputsthevalueof n [Link], n [Link],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,[Link] valuesof n ,[Link],ifthestartingvalueisapoweroftwo,thenthevalueof n willbeeveneachtimethroughtheloopuntilit [Link],startingwith16. Thehardquestioniswhetherwecanprovethatthisprogramterminatesfor allpositivevaluesof n .Sofar1,noonehasbeenabletoproveit ordisproveit! Exercise1 Rewritethefunction p r i n t _ n fromSection'5.8'usingiterationinsteadofrecursion.

b r e a k
[Link] 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 ! '
[Link]/wiki/Think_Python/Print_version 143/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Theloopconditionis T r u e ,whichisalwaystrue,sothelooprunsuntilithitsthebreakstatement. Eachtimethrough,[Link] d o n e ,the b r e a k [Link] [Link]:


>n o td o n e n o td o n e >d o n e D o n e !

Thiswayofwriting w h i l e loopsiscommonbecauseyoucanchecktheconditionanywhereintheloop(notjustatthetop)andyoucanexpressthestop conditionaffirmatively(stopwhenthishappens)ratherthannegatively(keepgoinguntilthathappens.).

Squareroots
Loopsareoftenusedinprogramsthatcomputenumericalresultsbystartingwithanapproximateansweranditerativelyimprovingit. Forexample,[Link] [Link] estimate, x,youcancomputeabetterestimatewiththefollowingformula: x+ a/ x 2

y=

Forexample,if ais4and xis3:


> > >a=4 . 0 > > >x=3 . 0 > > >y=( x+a / x )/2 > > >p r i n ty 2 . 1 6 6 6 6 6 6 6 6 6 7

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:

[Link]/wiki/Think_Python/Print_version

144/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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

When y= =x ,[Link], x ,andimprovesituntilitstopschanging:


w h i l eT r u e : p r i n tx y=( x+a / x )/2 i fy= =x : b r e a k x=y

Formostvaluesof a thisworksfine,butingeneralitisdangeroustotest f l o a t [Link]:mostrational numbers,like1/3,andirrationalnumbers,like2,cantberepresentedexactlywitha f l o a t . Ratherthancheckingwhether x and y areexactlyequal,itissafertousethebuiltinfunction a b s tocomputetheabsolutevalue,ormagnitude,ofthe differencebetweenthem:


i fa b s ( y x )<e p s i l o n : b r e a k

Where e p s i l o n hasavaluelike 0 . 0 0 0 0 0 0 1 thatdetermineshowcloseiscloseenough. Exercise2


[Link]/wiki/Think_Python/Print_version 145/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

' Encapsulatethisloopinafunctioncalled s q u a r e _ r o o t thattakes'a 'asaparameter,choosesareasonablevalueof'x ',andreturnsanestimateofthesquare rootof'a '.

Algorithms
Newtonsmethodisanexampleofan algorithm:itisamechanicalprocessforsolvingacategoryofproblems(inthiscase,computingsquareroots). [Link],you [Link],[Link]. Butifyouwerelazy,[Link],tofindtheproductof nand9,youcanwrite n1asthefirstdigitand10n [Link]! Similarly,thetechniquesyoulearnedforadditionwithcarrying,subtractionwithborrowing,[Link] [Link] simplesetofrules. Inmyopinion,itisembarrassingthathumansspendsomuchtimeinschoollearningtoexecutealgorithmsthat,quiteliterally,requirenointelligence. Ontheotherhand,theprocessofdesigningalgorithmsisinteresting,intellectuallychallenging,andacentralpartofwhatwecallprogramming. Someofthethingsthatpeopledonaturally,withoutdifficultyorconsciousthought,[Link] [Link],butsofarnoonehasbeenabletoexplain howwedoit,atleastnotintheformofanalgorithm.

Debugging
Asyoustartwritingbiggerprograms,[Link] placeforbugstohide. [Link],ifthereare100linesinyourprogramandyoucheckthemoneatatime,it wouldtake100steps. Instead,[Link],ornearit,[Link] p r i n t statement(or somethingelsethathasaverifiableeffect)andruntheprogram. Ifthemidpointcheckisincorrect,[Link],theproblemisinthesecondhalf. Everytimeyouperformachecklikethis,[Link](whichismuchlessthan100),youwouldbedown tooneortwolinesofcode,atleastintheory. [Link] [Link],[Link] youthinkthechancesareaboutthesamethatthebugisbeforeorafterthecheck.

Glossary
[Link]/wiki/Think_Python/Print_version 146/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 ' '

Thefirstcolumnisanumber,'a'thesecondcolumnisthesquarerootof'a'computedwiththefunctionfromExercise'7.2'thethirdcolumnisthesquare rootcomputedby'm a t h . s q r t 'thefourthcolumnistheabsolutevalueofthedifferencebetweenthetwoestimates.

Exercise4
Thebuiltinfunction'e v a l '[Link]:

[Link]/wiki/Think_Python/Print_version

147/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

' ' > > >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 ' > ' '

Writeafunctioncalled e v a l _ l o o p thatiterativelypromptstheuser,takestheresultinginputandevaluatesitusing'e v a l ',andprintstheresult. Itshouldcontinueuntiltheuserenters d o n e ,andthenreturnthevalueofthelastexpressionitevaluated.

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'[Link],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'.[Link]'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
[Link]/wiki/Think_Python/Print_version 148/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Files
Persistence
Mostoftheprogramswehaveseensofararetransientinthesensethattheyrunforashorttimeandproducesomeoutput,butwhentheyend,theirdata [Link],itstartswithacleanslate. Otherprogramsare persistent:theyrunforalongtime(orallthetime)theykeepatleastsomeoftheirdatainpermanentstorage(aharddrive,for example)andiftheyshutdownandrestart,theypickupwheretheyleftoff. Examplesofpersistentprogramsareoperatingsystems,whichrunprettymuchwheneveracomputerison,andwebservers,whichrunallthetime,waitingfor requeststocomeinonthenetwork. [Link] chapterswewillseeprogramsthatwritethem. [Link], p i c k l e ,thatmakesiteasyto storeprogramdata.

Readingandwriting
Atextfileisasequenceofcharactersstoredonapermanentmediumlikeaharddrive,flashmemory,[Link] 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 >

Ifthefilealreadyexists,openingitinwritemodeclearsouttheolddataandstartsfresh,sobecareful!Ifthefiledoesntexist,anewoneiscreated. The w r i t e methodputsdataintothefile.


> > >l i n e 1=" T h i sh e r e ' st h ew a t t l e , \ n " > > >f o u t . w r i t e ( l i n e 1 )

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 )
[Link]/wiki/Think_Python/Print_version 149/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Whenyouaredonewriting,youhavetoclosethefile.
> > >f o u t . c l o s e ( )

Formatoperator
Theargumentof w r i t e hastobeastring,soifwewanttoputothervaluesinafile,[Link] s t r :
> > >x=5 2 > > >f . w r i t e ( s t r ( x ) )

Analternativeistousethe formatoperator, % .Whenappliedtointegers, % [Link], % istheformat operator. Thefirstoperandisthe formatstring,[Link], 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 '

Theresultisthestring ' 4 2 ' ,whichisnottobeconfusedwiththeintegervalue 4 2 . Aformatsequencecanappearanywhereintheformatstring,soyoucanembedavalueinasentence:


> > >c a m e l s=4 2 > > >' Ih a v es p o t t e d% dc a m e l s . '%c a m e l s ' Ih a v es p o t t e d4 2c a m e l s . '

Theformatsequence ' % g ' formatsthenextelementinthetupleasafloatingpointnumber(dontaskwhy),and ' % s ' formatsthenextitemasastring:


> > >' I n% dy e a r sIh a v es p o t t e d% g% s . '%( 3 ,0 . 1 ,' c a m e l s ' ) ' I n3y e a r sIh a v es p o t t e d0 . 1c a m e l s . '

[Link],thetypesoftheelementshavetomatchtheformat sequences:

[Link]/wiki/Think_Python/Print_version

150/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >' % d% d% d '%( 1 ,2 ) T y p e E r r o r :n o te n o u g ha r g u m e n t sf o rf o r m a ts t r i n g > > >' % d '%' d o l l a r s ' T y p e E r r o r :i l l e g a la r g u m e n tt y p ef o rb u i l t i no p e r a t i o n

Inthefirstexample,therearentenoughelementsinthesecond,theelementisthewrongtype. [Link] 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 [Link] / h o m e / d i n s d a l e ,whichisthehomedirectoryofausernamed d i n s d a l e .

Astringlike c w d thatidentifiesafileiscalleda path.A relativepathstartsfromthecurrentdirectoryan absolutepathstartsfromthetopmostdirectoryin thefilesystem. Thepathswehaveseensofararesimplefilenames,[Link],youcanuse o s . p a t h . a b s p a t h :


> > >o s . p a t h . a b s p a t h ( ' m e m o . t x t ' ) ' / h o m e / d i n s d a l e / m e m o . t x t '
o s . p a t h . e x i s t s checkswhetherafileordirectoryexists:

> > >o s . p a t h . e x i s t s ( ' m e m o . t x t ' ) T r u 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 ' )
[Link]/wiki/Think_Python/Print_version 151/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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:

> > >o s . l i s t d i r ( c w d ) [ ' m u s i c ' ,' p h o t o s ' ,' m e m o . t x t ' ]

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 '[Link] inagivendirectoryanditssubdirectories.

Catchingexceptions
[Link],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:

[Link]/wiki/Think_Python/Print_version

152/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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

Toavoidtheseerrors,youcouldusefunctionslike o s . p a t h . e x i s t s and o s . p a t h . i s f i l e ,butitwouldtakealotoftimeandcodetocheckallthepossibilities(ifE r r n o 2 1 isanyindication,thereareatleast21thingsthatcangowrong). Itisbettertogoaheadandtry,anddealwithproblemsiftheyhappen,whichisexactlywhatthe t r y [Link] i f statement:


t r y : f i n=o p e n ( ' b a d _ f i l e ' ) f o rl i n ei nf i n : p r i n tl i n e f i n . c l o s e ( ) e x c e p t : p r i n t' S o m e t h i n gw e n tw r o n g . '

Pythonstartsbyexecutingthe t r y [Link],itskipsthe e x c e p t [Link],itjumpsoutofthe t r y clauseand executesthe e x c e p t clause. Handlinganexceptionwitha t r y statementiscalled [Link],the e x c e p t clauseprintsanerrormessagethatisnotveryhelpful. Ingeneral,catchinganexceptiongivesyouachancetofixtheproblem,ortryagain,oratleastendtheprogramgracefully.

Databases
A [Link] biggestdifferenceisthatthedatabaseisondisk(orotherpermanentstorage),soitpersistsaftertheprogramends. Themodule a n y d b m [Link],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 ' )

Themode ' c ' [Link](formostoperations)like [Link], a n y d b m updatesthedatabasefile.


[Link]/wiki/Think_Python/Print_version 153/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >d b [ ' c l e e s e . p n g ' ]=' P h o t oo fJ o h nC l e e s e . '

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 .

Manydictionarymethods,like k e y s and i t e m s ,[Link] f o r statement.


f o rk e yi nd b : p r i n tk e y

Aswithotherfiles,youshouldclosethedatabasewhenyouaredone:
> > >d b . c l o s e ( )

Pickling
Alimitationof a n y d b m [Link],yougetanerror. The p i c k l e [Link],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 . '

Theformatisntobvioustohumanreadersitismeanttobeeasyfor p i c k l e tointerpret. p i c k l e . l o a d s (loadstring)reconstitutestheobject:


> > >t 1=[ 1 ,2 ,3 ]
[Link]/wiki/Think_Python/Print_version 154/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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

Inotherwords,picklingandthenunpicklinghasthesameeffectascopyingtheobject. Youcanuse p i c k l e [Link],thiscombinationissocommonthatithasbeenencapsulatedinamodulecalled s h e l v e . Exercise3 IfyoudidExercise'12.4',modifyyoursolutionsothat itcreatesadatabasethatmapsfromeachwordinthelisttoalistofwordsthatusethesamesetof letters. Writeadifferentprogramthatopensthedatabaseandprintsthecontentsinahumanreadableformat.

Pipes
Mostoperatingsystemsprovideacommandlineinterface,alsoknownasa shell .Shellsusuallyprovidecommandstonavigatethefilesystemandlaunch [Link],inUnix,youcanchangedirectorieswith c d ,displaythecontentsofadirectorywith l s ,andlaunchawebbrowserbytyping(for example) f i r e f o x . AnyprogramthatyoucanlaunchfromtheshellcanalsobelaunchedfromPythonusinga [Link]. 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 )

[Link] l s processonelineatatimewith r e a d l i n e orgetthewholethingatoncewith r e a d :


> > >r e s=f p . r e a d ( )

Whenyouaredone,youclosethepipelikeafile:
[Link]/wiki/Think_Python/Print_version 155/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >s t a t=f p . c l o s e ( ) > > >p r i n ts t a t N o n e

Thereturnvalueisthefinalstatusofthe l s process N o n e meansthatitendednormally(withnoerrors). Acommonuseofpipesistoreadacompressedfileincrementallythatis,[Link] nameofacompressedfileasaparameterandreturnsapipethatuses g z i p todecompressthecontents:


d e fo p e n _ g z i p ( f i l e n a m e ) : c m d=' g u n z i pc'+f i l e n a m e f p=o s . p o p e n ( c m d ) r e t u r nf p

Ifyoureadlinesfrom f p oneatatime,youneverhavetostoretheuncompressedfileinmemoryorondisk.

Writingmodules
[Link],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,[Link]:
> > >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 :

[Link]/wiki/Think_Python/Print_version

156/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >w c . l i n e c o u n t ( ' w c . p y ' ) 7

SothatshowyouwritemodulesinPython. [Link],it definesnewfunctionsbutitdoesntexecutethem. Programsthatwillbeimportedasmodulesoftenusethefollowingidiom:


i f_ _ n a m e _ _= =' _ _ m a i n _ _ ' : p r i n tl i n e c o u n t ( ' w c . p y ' )
_ _ n a m e _ _ [Link], _ _ n a m e _ _ hasthevalue _ _ m a i n _ _ inthatcase,thetestcode

[Link],ifthemoduleisbeingimported,thetestcodeisskipped. Exercise4 Typethisexampleintoafilenamed'w c . p y '[Link]'i m p o r tw c '.Whatisthevalueof _ _ n a m e _ _ whenthemodule isbeingimported? Warning:Ifyouimportamodulethathasalreadybeenimported, [Link],evenifithaschanged. Ifyouwanttoreloadamodule,youcanusethebuiltinfunction'r e l o a d ',butitcanbetricky,sothesafestthingtodoisrestarttheinterpreterandthenimport themoduleagain.

Debugging
Whenyouarereadingandwritingfiles,[Link],tabsandnewlines arenormallyinvisible:
> > >s=' 12 \ t3 \ n4 ' > > >p r i n ts 12 3 4

Thebuiltinfunction r e p r [Link],itrepresentswhitespace characterswithbackslashsequences:


> > >p r i n tr e p r ( s ) ' 12 \ t3 \ n4 '

Thiscanbehelpfulfordebugging.
[Link]/wiki/Think_Python/Print_version 157/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],represented \ n .Othersuseareturncharacter,represented \ r .[Link],theseinconsistenciesmightcauseproblems. Formostsystems,[Link](andreadmoreaboutthisissue)at w i k i p e d i a . o r g / w i k i / N e w l i n e . Or,ofcourse,youcouldwriteoneyourself.

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 '[Link] messagefrom't h i n k p y t h o n . c o m ':
[Link]/wiki/Think_Python/Print_version 158/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

i m p o r tu r l l i b c o n n=u r l l i b . u r l o p e n ( ' h t t p : / / t h i n k p y t h o n . c o m / s e c r e t . h t m l ' ) f o rl i n ei nc o n n . f p : p r i n tl i n e . s t r i p ( )

Runthiscodeandfollowtheinstructionsyouseethere. Exercise6 InalargecollectionofMP3files,theremaybemorethanonecopyofthesamesong,[Link] thisexerciseistosearchfortheseduplicates. Writeaprogramthatsearchesadirectoryandallofits subdirectories,recursively,andreturnsalistofcompletepathsforallfileswithagivensuffix(like'. m p 3 ').Hint:'o s . p a t h 'providesseveralusefulfunctionsfor manipulatingfileandpathnames. Torecognizeduplicates,youcanuseahashfunctionthat [Link],MD5(MessageDigestalgorithm5)takesanarbitrarilylongmessageandreturns [Link]. 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 [Link],soitisreasonably [Link],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,[Link]'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 '[Link],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, [Link],[Link]:
' ' 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 )
[Link]/wiki/Think_Python/Print_version 159/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

' '

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 [Link]. 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 [Link]'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
[Link],wewillcreateatypecalled P o i n t thatrepresentsapoint intwodimensionalspace. Inmathematicalnotation,[Link],(0,0)representstheorigin,and(x, y)representsthepoint xunitstotherightand yunitsupfromtheorigin. ThereareseveralwayswemightrepresentpointsinPython: Wecouldstorethecoordinatesseparatelyintwovariables, x and y . Wecouldstorethecoordinatesaselementsinalistortuple. Wecouldcreateanewtypetorepresentpointsasobjects. Creatinganewtypeis(alittle)morecomplicatedthantheotheroptions,butithasadvantagesthatwillbeapparentsoon. Auserdefinedtypeisalsocalleda [Link]:
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 " " "

Thisheaderindicatesthatthenewclassisa P o i n t ,whichisakindof o b j e c t ,whichisabuiltintype.


[Link]/wiki/Think_Python/Print_version 160/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],butwewillgetbacktothatlater. Definingaclassnamed P o i n t createsaclassobject.


> > >p r i n tP o i n t < c l a s s' _ _ m a i n _ _ . P o i n t ' >

Because P o i n t isdefinedatthetoplevel,itsfullnameis _ _ m a i n _ _ . P o i n t . [Link],youcall P o i n t asifitwereafunction.


> > >b l a n k=P o i n t ( ) > > >p r i n tb l a n k < _ _ m a i n _ _ . P o i n ti n s t a n c ea t0 x b 7 e 9 d 3 a c >

ThereturnvalueisareferencetoaPointobject,whichweassignto b l a n k .Creatinganewobjectiscalled instantiation,andtheobjectisan instanceofthe class. Whenyouprintaninstance,Pythontellsyouwhatclassitbelongstoandwhereitisstoredinmemory(theprefix 0 x meansthatthefollowingnumberisin hexadecimal).

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 [Link] attributes. Asanoun,ATtributeispronouncedwithemphasisonthefirstsyllable,asopposedtoaTRIBute,whichisaverb. [Link] objectdiagram: <IMGSRC="[Link]"> Thevariable b l a n k referstoaPointobject,[Link]. Youcanreadthevalueofanattributeusingthesamesyntax:
> > >p r i n tb l a n k . y
[Link]/wiki/Think_Python/Print_version 161/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

4 . 0 > > >x=b l a n k . x > > >p r i n tx 3 . 0

Theexpression b l a n k . x means,Gototheobject b l a n k referstoandgetthevalueof x .Inthiscase,weassignthatvaluetoavariablenamed x .Thereisno conflictbetweenthevariable x andtheattribute x . [Link]:


> > >p r i n t' ( % g ,% g ) '%( b l a n k . x ,b l a n k . y ) ( 3 . 0 ,4 . 0 ) > > >d i s t a n c e=m a t h . s q r t ( b l a n k . x * * 2+b l a n k . y * * 2 ) > > >p r i n td i s t a n c e 5 . 0

[Link]:
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 [Link],youcanpass b l a n k asanargument:

> > >p r i n t _ p o i n t ( b l a n k ) ( 3 . 0 ,4 . 0 )

Insidethefunction, p isanaliasfor b l a n k ,soifthefunctionmodifies p , b l a n k changes.

Exercise1
Writeafunctioncalled'd i s t a n c e 'thatittakestwoPointsasargumentsandreturnsthedistancebetweenthem.

Rectangles
Sometimesitisobviouswhattheattributesofanobjectshouldbe,[Link],imagineyouaredesigninga [Link]?Youcanignoreangletokeepthingssimple, assumethattherectangleiseitherverticalorhorizontal. Thereareatleasttwopossibilities: Youcouldspecifyonecorneroftherectangle(orthecenter),thewidth,andtheheight.
[Link]/wiki/Think_Python/Print_version 162/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Youcouldspecifytwoopposingcorners. Atthispointitishardtosaywhethereitherisbetterthantheother,sowellimplementthefirstone,justasanexample. Hereistheclassdefinition:


c l a s sR e c t a n g l e ( o b j e c t ) : " " " r e p r e s e n tar e c t a n g l e . a t t r i b u t e s :w i d t h ,h e i g h t ,c o r n e r . " " "

Thedocstringliststheattributes: w i d t h and h e i g h t arenumbers c o r n e r isaPointobjectthatspecifiesthelowerleftcorner. Torepresentarectangle,youhavetoinstantiateaRectangleobjectandassignvaluestotheattributes:


b o x=R e c t a n g l e ( ) b o x . w i d t h=1 0 0 . 0 b o x . h e i g h t=2 0 0 . 0 b o x . c o r n e r=P o i n t ( ) b o x . c o r n e r . x=0 . 0 b o x . c o r n e r . y=0 . 0

Theexpression b o x . c o r n e r . x means,Gototheobject b o x referstoandselecttheattributenamed c o r n e r thengotothatobjectandselecttheattributenamed x . Thefigureshowsthestateofthisobject: <IMGSRC="[Link]"> Anobjectthatisanattributeofanotherobjectis embedded.

Instancesasreturnvalues
[Link], 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 :
[Link]/wiki/Think_Python/Print_version 163/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >c e n t e r=f i n d _ c e n t e r ( b o x ) > > >p r i n t _ p o i n t ( c e n t e r ) ( 5 0 . 0 ,1 0 0 . 0 )

Objectsaremutable
[Link],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

[Link], g r o w _ r e c t a n g l e takesaRectangleobjectandtwonumbers, d w i d t h and d h e i g h t ,andaddsthe numberstothewidthandheightoftherectangle:


d e fg r o w _ r e c t a n g l e ( r e c t ,d w i d t h ,d h e i g h t ): r e c t . w i d t h+ =d w i d t h r e c t . h e i g h t+ =d h e i g h t

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

Insidethefunction, r e c t isanaliasfor b o x ,soifthefunctionmodifies r e c t , b o x changes.

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
[Link] [Link]/wiki/Think_Python/Print_version 164/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link] variablesthatmightrefertoagivenobject. [Link] c o p y modulecontainsafunctioncalled c o p y thatcanduplicateanyobject:


> > >p 1=P o i n t ( ) > > >p 1 . x=3 . 0 > > >p 1 . y=4 . 0 > > >i m p o r tc o p y > > >p 2=c o p y . c o p y ( p 1 )
p 1 and p 2 containthesamedata,buttheyarenotthesamePoint.

> > >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,[Link] = = toyield T r u e becausethesepoints [Link],youwillbedisappointedtolearnthatforinstances,thedefaultbehaviorofthe = = operatoristhesameasthe i s operator itchecksobjectidentity,[Link]. 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

Hereiswhattheobjectdiagramlookslike: <IMGSRC="[Link]"> Thisoperationiscalleda shallowcopybecauseitcopiestheobjectandanyreferencesitcontains,butnottheembeddedobjects. Formostapplications,[Link],invoking g r o w _ r e c t a n g l e ononeoftheRectangleswouldnotaffecttheother,butinvoking m o v e _ r e c t a n g l e oneitherwouldaffectboth!Thisbehaviorisconfusinganderrorprone.


[Link]/wiki/Think_Python/Print_version 165/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Fortunately,the c o p y modulecontainsamethodnamed d e e p c o p y thatcopiesnotonlytheobjectbutalsotheobjectsitrefersto,andtheobjects theyreferto, [Link] deepcopy.


> > >b o x 3=c o p y . d e e p c o p y ( b o x ) > > >b o x 3i sb o x F a l s e > > >b o x 3 . c o r n e ri sb o x . c o r n e r F a l s e
b o x 3 and b o x arecompletelyseparateobjects.

Exercise3
Writeaversionof m o v e _ r e c t a n g l e thatcreatesandreturnsanewRectangleinsteadofmodifyingtheoldone.

Debugging
Whenyoustartworkingwithobjects,[Link],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
[Link]/wiki/Think_Python/Print_version 166/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

class: [Link]. classobject: [Link]. 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:

' ' f r o mW o r l di m p o r t* w o r l d=W o r l d ( ) w a i t _ f o r _ u s e r ( ) ' '

Awindowshouldappearwithatitlebarandanemptysquare. InthisexercisewewillusethiswindowtodrawPoints,[Link] followinglinesbefore w a i t _ f o r _ u s e r andruntheprogramagain


' ' c a n v a s=w o r l d . c a ( w i d t h = 5 0 0 ,h e i g h t = 5 0 0 ,b a c k g r o u n d = ' w h i t e ' ) b b o x=[ [ 1 5 0 , 1 0 0 ] ,[ 1 5 0 ,1 0 0 ] ] c a n v a s . r e c t a n g l e ( b b o x ,o u t l i n e = ' b l a c k ' ,w i d t h = 2 ,f i l l = ' g r e e n 4 ' ) ' '

Youshouldseeagreenrectanglewithablackoutline. ThefirstlinecreatesaCanvas,[Link] 167/282 [Link]/wiki/Think_Python/Print_version

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Youshouldseeagreenrectanglewithablackoutline. ThefirstlinecreatesaCanvas,[Link] providesmethodslike'r e c t a n g l e 'fordrawingvariousshapes.


b b o x ''[Link]

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 [Link] d r a w _ c i r c l e thatdrawscirclesonthecanvas. WriteaprogramthatdrawsthenationalflagofoftheCzechRepublic([Link] 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 ' ) ' '

Ihavewrittenasmallprogramthatliststheavailablecolors youcandownloaditfrom't h i n k p y t h o n . c o m / c o d e / c o l o r _ l i s t . p y '.

Classesandfunctions
[Link]/wiki/Think_Python/Print_version 168/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Time
Asanotherexampleofauserdefinedtype,we'lldefineaclasscalled T i m e [Link]:
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="[Link]">

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,[Link]:[Link] 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 ) :
[Link]/wiki/Think_Python/Print_version 169/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

s u m=T i m e ( ) s u m . h o u r=t 1 . h o u r+t 2 . h o u r s u m . m i n u t e=t 1 . m i n u t e+t 2 . m i n u t e s u m . s e c o n d=t 1 . s e c o n d+t 2 . s e c o n d r e t u r ns u m

Thefunctioncreatesanew T i m e object,initializesitsattributes,[Link] 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

Theresult, 1 0 : 8 0 : 0 0 [Link] [Link],wehavetocarrytheextrasecondsintotheminutecolumnortheextraminutesintothehourcolumn. Heresanimprovedversion:


d e fa d d _ t i m e ( t 1 ,t 2 ) : s u m=T i m e ( ) s u m . h o u r=t 1 . h o u r+t 2 . h o u r s u m . m i n u t e=t 1 . m i n u t e+t 2 . m i n u t e s u m . s e c o n d=t 1 . s e c o n d+t 2 . s e c o n d i fs u m . s e c o n d> =6 0 : s u m . s e c o n d=6 0 s u m . m i n u t e+ =1 i fs u m . m i n u t e> =6 0 : s u m . m i n u t e=6 0 s u m . h o u r+ =1
[Link]/wiki/Think_Python/Print_version 170/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

r e t u r ns u m

Althoughthisfunctioniscorrect,[Link].

Modifiers
[Link],[Link] wayarecalled modifiers.
i n c r e m e n t ,whichaddsagivennumberofsecondstoa T i m e object,[Link]:

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 i ft i m e . s e c o n d> =6 0 : t i m e . s e c o n d=6 0 t i m e . m i n u t e+ =1 i ft i m e . m i n u t e> =6 0 : t i m e . m i n u t e=6 0 t i m e . h o u r+ =1

Thefirstlineperformsthebasicoperationtheremainderdealswiththespecialcaseswesawbefore. Isthisfunctioncorrect?Whathappensiftheparameter s e c o n d s ismuchgreaterthansixty? Inthatcase,itisnotenoughtocarryoncewehavetokeepdoingituntil t i m e . s e c o n d [Link] i f statementswith w h i l e [Link],butnotveryefficient. Exercise3 Writeacorrectversionof'i n c r e m e n t 'thatdoesntcontainanyloops. [Link],[Link] [Link] times,andfunctionalprogramstendtobelessefficient. Ingeneral,[Link] mightbecalleda functional programmingstyle. Exercise4 Writeapureversionof'i n c r e m e n t 'thatcreatesandreturnsanewTimeobjectratherthanmodifyingtheparameter.

[Link]/wiki/Think_Python/Print_version

171/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Prototypingversusplanning
[Link],Iwroteaprototypethatperformedthebasiccalculationandthen testedit,patchingerrorsalongtheway. Thisapproachcanbeeffective,[Link] unnecessarilycomplicatedsinceitdealswithmanyspecialcasesandunreliablesinceitishardtoknowifyouhavefoundalltheerrors. Analternativeis planneddevelopment,[Link],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

AndhereisthefunctionthatconvertsintegerstoTimes(recallthat d i v m o d dividesthefirstargumentbythesecondandreturnsthequotientandremainderasa tuple).


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

Youmighthavetothinkabit,andrunsometests,[Link] t i m e _ t o _ i n t ( i n t _ t o _ t i m e ( x ) )= =x formanyvaluesof x .Thisisanexampleofaconsistencycheck. Onceyouareconvincedtheyarecorrect,youcanusethemtorewrite a d d _ t i m e :


d e fa d d _ t i m e ( t 1 ,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 )

Thisversionisshorterthantheoriginal,andeasiertoverify.
[Link]/wiki/Think_Python/Print_version 172/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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,[Link] 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. [Link],[Link] [Link]. 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 [Link],iftheyarenottrue,thensomethinghasgone wrong. [Link],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:

d e fa d d _ t i m e ( t 1 ,t 2 ) : i fn o tv a l i d _ t i m e ( t 1 )o rn o tv a l i d _ t i m e ( t 2 ) : r a i s eV a l u e E r r o r ,' i n v a l i dT i m eo b j e c ti na d d _ t i m e ' 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 )

Oryoucouldusean a s s e r t statement,whichchecksagiveninvariantandraisesanexceptionifitfails:
[Link]/wiki/Think_Python/Print_version 173/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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: [Link]. modifier: [Link]. 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
[Link]/wiki/Think_Python/Print_version 174/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

The'd a t e t i m e 'moduleprovides'd a t e 'and't i m e 'objectsthataresimilartotheDateandTimeobjectsinthischapter,buttheyprovidearichsetofmethodsand [Link]'d o c s . p y t h o n . o r g / l i b / d a t e t i m e d a t e . h t m l '. Usethe'd a t e t i m e 'moduletowriteaprogramthatgetsthecurrentdateandprintsthedayoftheweek. Writeaprogramthattakesabirthdayasinputandprintstheusersageandthenumberofdays,hours,minutesandsecondsuntiltheirnextbirthday.

Classesandmethods
Objectorientedfeatures
Pythonisan objectorientedprogramminglanguage,whichmeansthatitprovidesfeaturesthatsupportobjectorientedprogramming. Itisnoteasytodefineobjectorientedprogramming,butwehavealreadyseensomeofitscharacteristics: Programsaremadeupofobjectdefinitionsandfunction definitions,andmostofthecomputationisexpressedintermsofoperationsonobjects. Eachobjectdefinitioncorrespondstosomeobjectorconcept intherealworld,andthefunctionsthatoperateonthatobjectcorrespondtothewaysrealworldobjectsinteract. Forexample,the T i m e classdefinedinChapter16correspondstothewaypeoplerecordthetimeofday,andthefunctionswedefinedcorrespondtothekinds [Link],the P o i n t and R e c t a n g l e classescorrespondtothemathematicalconceptsofapointandarectangle. Sofar,[Link] [Link],thealternativeismoreconciseandmoreaccuratelyconveysthe structureoftheprogram. Forexample,inthe T i m e program,[Link], itisapparentthateveryfunctiontakesatleastone T i m e objectasanargument. Thisobservationisthemotivationfor [Link],lists, [Link],wewilldefinemethodsforuserdefinedtypes. Methodsaresemanticallythesameasfunctions,buttherearetwosyntacticdifferences: Methodsaredefinedinsideaclassdefinitioninordertomaketherelationshipbetweentheclassandthemethodexplicit. Thesyntaxforinvokingamethodisdifferentfromthesyntaxforcallingafunction. Inthenextfewsections,[Link] [Link],youwillbeabletochoosethebestformfor whateveryouaredoing.
[Link]/wiki/Think_Python/Print_version 175/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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,[Link].
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

Inthisuseofdotnotation, T i m e isthenameoftheclass,and p r i n t _ t i m e isthenameofthemethod. s t a r t ispassedasaparameter. Thesecond(andmoreconcise)wayistousemethodsyntax:


> > >s t a r t . p r i n t _ t i m e ( ) 0 9 : 4 5 : 0 0

Inthisuseofdotnotation, p r i n t _ t i m e isthenameofthemethod(again),and s t a r t istheobjectthemethodisinvokedon,whichiscalledthe [Link] thesubjectofasentenceiswhatthesentenceisabout,thesubjectofamethodinvocationiswhatthemethodisabout.


[Link]/wiki/Think_Python/Print_version 176/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Insidethemethod,thesubjectisassignedtothefirstparameter,sointhiscase s t a r t isassignedto t i m e . Byconvention,thefirstparameterofamethodiscalled s e l f ,soitwouldbemorecommontowrite p r i n t _ t i m e likethis:


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 ( s e l f ) : p r i n t' % . 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 )

Thereasonforthisconventionisanimplicitmetaphor: Thesyntaxforafunctioncall, p r i n t _ t i m e ( s t a r t ) , [Link],Hey p r i n t _ t i m e !Heresanobjectforyoutoprint. Inobjectorientedprogramming,theobjectsaretheactive [Link] s t a r t . p r i n t _ t i m e ( ) saysHey s t a r t !Pleaseprintyourself. Thischangeinperspectivemightbemorepolite,[Link],[Link] shiftingresponsibilityfromthefunctionsontotheobjectsmakesitpossibletowritemoreversatilefunctions,andmakesiteasiertomaintainandreusecode.

Exercise1
Rewrite t i m e _ t o _ i n t (fromSection'16.4')[Link] 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 )

Thisversionassumesthat t i m e _ t o _ i n t iswrittenasamethod,[Link],notethatitisapurefunction,notamodifier. Hereshowyouwouldinvoke i n c r e m e n t :


> > >s t a r t . p r i n t _ t i m e ( ) 0 9 : 4 5 : 0 0
[Link]/wiki/Think_Python/Print_version 177/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >e n d=s t a r t . i n c r e m e n t ( 1 3 3 7 ) > > >e n d . p r i n t _ t i m e ( ) 1 0 : 0 7 : 1 7

Thesubject, s t a r t ,getsassignedtothefirstparameter, s e l f .Theargument, 1 3 3 7 ,getsassignedtothesecondparameter, s e c o n d s . Thismechanismcanbeconfusing,[Link],ifyouinvoke i n c r e m e n t withtwoarguments,youget:


> > >e n d=s t a r t . i n c r e m e n t ( 1 3 3 7 ,4 6 0 ) T y p e E r r o r :i n c r e m e n t ( )t a k e se x a c t l y2a r g u m e n t s( 3g i v e n )

Theerrormessageisinitiallyconfusing,[Link],soalltogether thatsthree.

Amorecomplicatedexample
i s _ a f t e r (fromExercise16.2)[Link]

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)[Link] _ _ 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
[Link]/wiki/Think_Python/Print_version 178/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

s e l f . s e c o n d=s e c o n d

Itiscommonfortheparametersof _ _ i n i t _ _ [Link]
s e l f . h o u r=h o u r

storesthevalueoftheparameter h o u r asanattributeof s e l f . Theparametersareoptional,soifyoucall T i m e withnoarguments,yougetthedefaultvalues.


> > >t i m e=T i m e ( ) > > >t i m e . p r i n t _ t i m e ( ) 0 0 : 0 0 : 0 0

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 :
[Link]/wiki/Think_Python/Print_version 179/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Whenyou p r i n t anobject,Pythoninvokesthe s t r method:


> > >t i m e=T i m e ( 9 ,4 5 ) > > >p r i n tt i m e 0 9 : 4 5 : 0 0

WhenIwriteanewclass,Ialmostalwaysstartbywriting _ _ i n i t _ _ ,whichmakesiteasiertoinstantiateobjects,and _ _ s t r _ _ ,whichisusefulfordebugging.

Exercise3
Writea's t r 'methodforthe'P o i n t '[Link].

Operatoroverloading
Bydefiningotherspecialmethods,[Link],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

Whenyouapplythe + operatortoTimeobjects,Pythoninvokes _ _ a d d _ _ .Whenyouprinttheresult,Pythoninvokes _ _ s t r _ _ .Sothereisquitealothappening behindthescenes! Changingthebehaviorofanoperatorsothatitworkswithuserdefinedtypesiscalled [Link] correspondingspecialmethod,like _ _ a d d _ _ .Formoredetails,see d o c s . p y t h o n . o r g / r e f / s p e c i a l n a m e s . h t m l .


[Link]/wiki/Think_Python/Print_version 180/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Exercise4
Writean'a d d 'methodforthePointclass.

Typebaseddispatch
IntheprevioussectionweaddedtwoTimeobjects,[Link] _ _ 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,[Link],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 '

[Link]/wiki/Think_Python/Print_version

181/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Theproblemis,insteadofaskingtheTimeobjecttoaddaninteger,PythonisaskinganintegertoaddaTimeobject,[Link] thereisacleversolutionforthisproblem:thespecialmethod _ _ r a d d _ _ ,[Link] therightsideofthe + [Link]:


#i n s i d ec l a s sT i m e : d e f_ _ r a d d _ _ ( s e l f ,o t h e r ) : r e t u r ns e l f . _ _ a d d _ _ ( o t h e r )

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)[Link] forargumentswithdifferenttypes. [Link],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 .
[Link]/wiki/Think_Python/Print_version 182/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

> > >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 }

Functionsthatcanworkwithseveraltypesarecalled [Link],thebuiltinfunction s u m ,whichadds theelementsofasequence,worksaslongastheelementsofthesequencesupportaddition. SinceTimeobjectsprovidean a d d method,theyworkwith s u m :


> > >t 1=T i m e ( 7 ,4 3 ) > > >t 2=T i m e ( 7 ,4 1 ) > > >t 3=T i m e ( 7 ,3 7 ) > > >t o t a l=s u m ( [ t 1 ,t 2 ,t 3 ] ) > > >p r i n tt o t a l 2 3 : 0 1 : 0 0

Ingeneral,ifalloftheoperationsinsideafunctionworkwithagiventype,thenthefunctionworkswiththattype. Thebestkindofpolymorphismistheunintentionalkind,whereyoudiscoverthatafunctionyoualreadywrotecanbeappliedtoatypeyouneverplannedfor.

Debugging
Itislegaltoaddattributestoobjectsatanypointintheexecutionofaprogram,butifyouareasticklerfortypetheory,itisadubiouspracticetohaveobjects [Link]. 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.
[Link]/wiki/Think_Python/Print_version 183/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 184/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

asolutiontothepreviousproblemwithonebig,[Link].''Ifyougetstuck,youcandownload'''t h i n k p y t h o n . c o m / c o d e / G o o d K a n g a r o o . p y ''', whichexplainstheproblemanddemonstratesasolution.'

Exercise7
[Link],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 ').

Ifyourunthiscode,[Link],youcanzoominand [Link],butwithonlyonesphereintheworld,itishardtotellthedifference. Thefollowingloopcreatesacubeofspheres:


' ' 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 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 ) ' '

Putthiscodeinascriptandmakesureitworksfor you. Modifytheprogramsothateachsphereinthecube hasthecolorthatcorrespondstoitspositioninRGBspace.Noticethatthecoordinatesareintherange0255,buttheRGBtuplesareintherange0.01.0. Download't h i n k p y t h o n . c o m / c o d e / c o l o r _ l i s t . p y '


[Link]/wiki/Think_Python/Print_version 185/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

andusethefunction r e a d _ c o l o r s togeneratealistoftheavailablecolorsonyoursystem,[Link] thepositionthatcorrespondstoitsRGBvalues. Youcanseemysolutionat't h i n k p y t h o n . c o m / c o d e / c o l o r _ s p a c e . p y '.

Furtherreading
Wikipedia:VPython Wikipedia:RGBcolormodel

Inheritance
Inthischapterwewilldevelopclassestorepresentplayingcards,decksofcards,[Link],youcanreadaboutitat w i k i p e d i a . o r g / w i k i / P o k e r ([Link] 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 ([Link]

Cardobjects
Therearefiftytwocardsinadeck,[Link],Hearts,Diamonds,andClubs (indescendingorderinbridge).TheranksareAce,2,3,4,5,6,7,8,9,10,Jack,Queen,[Link],anAcemay behigherthanKingorlowerthan2. Ifwewanttodefineanewobjecttorepresentaplayingcard,itisobviouswhattheattributesshouldbe: r a n k and s u i t .Itisnotasobviouswhattypethe [Link] ' S p a d e ' forsuitsand ' Q u e e n ' [Link] wouldnotbeeasytocomparecardstoseewhichhadahigherrankorsuit. Analternativeistouseintegersto [Link],encodemeansthatwearegoingtodefineamappingbetweennumbersand suits,[Link](thatwouldbeencryption). Forexample,thistableshowsthesuitsandthecorrespondingintegercodes: Spades Hearts 3 2

Diamonds 1 Clubs 0

Thiscodemakesiteasytocomparecardsbecausehighersuitsmaptohighernumbers,wecancomparesuitsbycomparingtheircodes. Themappingforranksisfairlyobviouseachofthenumericalranksmapstothecorrespondinginteger,andforfacecards:
[Link]/wiki/Think_Python/Print_version 186/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Jack

11

Queen 12 King 13

Iamusingthe [Link],buttheydontappear explicitlyinthecode. Theclassdefinitionfor C a r d lookslikethis:


c l a s sC a r d : " " " r e p r e s e n t sas t a n d a r dp l a y i n gc a r d . " " " 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

Asusual,theinitmethodtakesanoptionalparameterforeachattribute.Thedefaultcardisthe2ofClubs. TocreateaCard,youcall C a r d withthesuitandrankofthecardyouwant.


q u e e n _ o f _ d i a m o n d s=C a r d ( 1 ,1 2 )

Classattributes
InordertoprintCardobjectsinawaythatpeoplecaneasilyread,[Link] [Link] 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 ] )

Variableslike s u i t _ n a m e s and r a n k _ n a m e s ,whicharedefinedinsideaclassbutoutsideofanymethod,arecalledclassattributesbecausetheyareassociatedwith theclassobject C a r d . Thistermdistinguishedthemfromvariableslike s u i t and r a n k ,whicharecalled instanceattributesbecausetheyareassociatedwithaparticularinstance.


[Link]/wiki/Think_Python/Print_version 187/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],in _ _ s t r _ _ , s e l f isaCardobject,and s e l f . r a n k [Link], 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 [Link] N o n e asaplacekeeper,wegetamappingwiththenicepropertythat theindex2mapstothestring ' 2 ' ,[Link],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

Hereisadiagramthatshowsthe C a r d classobjectandoneCardinstance: <IMGSRC="[Link]">


C a r d isaclassobject,soithastype t y p e . c a r d 1 hastype C a r d .(Tosavespace,Ididntdrawthecontentsof s u i t _ n a m e s and r a n k _ n a m e 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

iftheyareequaltoeachother. [Link],whichisbetter,the3ofClubsorthe2ofDiamonds?Onehasahigherrank,buttheotherhasa [Link],youhavetodecidewhetherrankorsuitismoreimportant. Theanswermightdependonwhatgameyouareplaying,buttokeepthingssimple,wellmakethearbitrarychoicethatsuitismoreimportant,soallofthe SpadesoutrankalloftheDiamonds,andsoon. Withthatdecided,wecanwrite _ _ c m p _ _ :


#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 ) : #c h e c kt h es u i t s i fs e l f . s u i t>o t h e r . s u i t :r e t u r n1
[Link]/wiki/Think_Python/Print_version 188/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

i fs e l f . s u i t<o t h e r . s u i t :r e t u r n1 #s u i t sa r et h es a m e . . .c h e c kr a n k s i fs e l f . r a n k>o t h e r . r a n k :r e t u r n1 i fs e l f . r a n k<o t h e r . r a n k :r e t u r n1 #r a n k sa r et h es a m e . . .i t ' sat i e r e t u r n0

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 )

Thebuiltinfunction c m p hasthesameinterfaceasthemethod _ _ c m p _ _ :ittakestwovaluesandreturnsapositivenumberifthefirstislarger,anegativenumber ofthesecondislarger,and0iftheyareequal.

Exercise1
Writea _ _ c m p _ _ [Link]:youcanusetuplecomparison,butyoualsomightconsiderusingintegersubtraction.

Decks
NowthatwehaveCards,[Link],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 [Link],andappendsitto s e l f . c a r d s .
[Link]/wiki/Think_Python/Print_version 189/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Thismethoddemonstratesanefficientwaytoaccumulatealargestring:buildingalistofstringsandthenusing j o i n .Thebuiltinfunction s t r invokesthe _ _ s t r _ _ methodoneachcardandreturnsthestringrepresentation. Sinceweinvoke j o i n onanewlinecharacter,[Link]:


> > >d e c k=D e c k ( ) > > >p r i n td e c k A c eo fC l u b s 2o fC l u b s 3o fC l u b s . . . 1 0o fS p a d e s J a c ko fS p a d e s Q u e e no fS p a d e s K i n go fS p a d e s

Eventhoughtheresultappearson52lines,itisonelongstringthatcontainsnewlines.

Add,remove,shuffleandsort
Todealcards,[Link] 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 ( )

Since p o p removesthe last cardinthelist,wearedealingfromthebottomofthedeck.Inreallifebottomdealingisfrownedupon1,butinthiscontextitsok. Toaddacard,wecanusethelistmethod a p p e n d :


# i n s i d ec l a s sD e c k :
[Link]/wiki/Think_Python/Print_version 190/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

Amethodlikethisthatusesanotherfunctionwithoutdoingmuchrealworkissometimescalleda [Link],whereitis commontoglueathinlayerofgoodqualitywoodtothesurfaceofacheaperpieceofwood. Inthiscasewearedefiningathinmethodthatexpressesalistoperationintermsthatareappropriatefordecks. Asanotherexample,wecanwriteaDeckmethodnamed s h u f f l e usingthefunction s h u f f l e fromthe r a n d o m module:


#i n s i d ec l a s sD e c k : d e fs h u f f l e ( s e l f ) : r a n d o m . s h u f f l e ( s e l f . c a r d s )

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 [Link] versionofanexistingclass. [Link],theexistingclassiscalledthe parentand thenewclassiscalledthe child. Asanexample,letssaywewantaclasstorepresentahand,thatis,[Link]:botharemadeupofa setofcards,andbothrequireoperationslikeaddingandremovingcards. [Link],inpokerwemightcomparetwo [Link],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 " " "

[Link]/wiki/Think_Python/Print_version

191/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Thisdefinitionindicatesthat H a n d inheritsfrom D e c k thatmeanswecanusemethodslike p o p _ c a r d and a d d _ c a r d forHandsaswellasDecks.


H a n d alsoinherits _ _ i n i t _ _ from D e c k ,butitdoesntreallydowhatwewant:insteadofpopulatingthehandwith52newcards,theinitmethodforHandsshould

initialize c a r d s withanemptylist. Ifweprovideaninitmethodinthe H a n d class,itoverridestheoneinthe D e c k class:


#i n s i d ec l a s sH a n d : 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

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

Buttheothermethodsareinheritedfrom D e c k ,sowecanuse p o p _ c a r d and a d d _ c a r d todealacard:


> > >d e c k=D e c k ( ) > > >c a r d=d e c k . p o p _ c a r d ( ) > > >h a n d . a d d _ c a r d ( c a r d ) > > >p r i n th a n d K i n go fS p a d e s

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,[Link] s e l f and h a n d ,andreturns N o n e .

Insomegames,cardsaremovedfromonehandtoanother,[Link] m o v e _ c a r d s foranyoftheseoperations: s e l f canbe eitheraDeckoraHand,and h a n d ,despitethename,canalsobea D e c k .

[Link]/wiki/Think_Python/Print_version

192/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Exercise3 WriteaDeckmethodcalled d e a l _ h a n d s thattakestwoparameters,thenumberofhandsandthenumberofcardsperhand,andthatcreatesnewHandobjects, dealstheappropriatenumberofcardsperhand,andreturnsalistofHandobjects. [Link] codereuse,[Link],theinheritancestructurereflectsthenatural structureoftheproblem,whichmakestheprogrameasiertounderstand. Ontheotherhand,[Link],[Link] [Link],manyofthethingsthatcanbedoneusinginheritancecanbedoneaswellorbetterwithoutit.

Classdiagrams
Sofarwehaveseenstackdiagrams,whichshowthestateofaprogram,andobjectdiagrams,[Link] diagramsrepresentasnapshotintheexecutionofaprogram,sotheychangeastheprogramruns. Theyarealsohighlydetailedforsomepurposes,[Link] showingindividualobjects,itshowsclassesandtherelationshipsbetweenthem. Thereareseveralkindsofrelationshipbetweenclasses: [Link],eachRectanglecontainsareferencetoaPoint,andeachDeck [Link] HASA,asin,aRectanglehasaPoint. [Link] ISA,asin,aHandisakindofaDeck. Oneclassmightdependonanotherinthesensethatchangesinoneclasswouldrequirechangesintheother. A [Link],thisdiagramshowstherelationshipsbetween C a r d , D e c k and H a n d . <IMGSRC="[Link]"> ThearrowwithahollowtriangleheadrepresentsanISArelationshipinthiscaseitindicatesthatHandinheritsfromDeck. ThestandardarrowheadrepresentsaHASArelationshipinthiscaseaDeckhasreferencestoCardobjects. Thestar(* )nearthearrowheadisa [Link],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.
[Link]/wiki/Think_Python/Print_version 193/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Debugging
Inheritancecanmakedebuggingachallengebecausewhenyouinvokeamethodonanobject,youmightnotknowwhichmethodwillbeinvoked. [Link],likePokerHands,BridgeHands,[Link] invokeamethodlike s h u f f l e ,youmightgettheonedefinedin D e c k ,butifanyofthesubclassesoverridethismethod,youllgetthatversioninstead. Anytimeyouareunsureabouttheflowofexecutionthroughyourprogram,thesimplestsolutionistoaddprintstatementsatthebeginningoftherelevant [Link] 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)[Link].

Heresaprogramdesignsuggestion:wheneveryouoverrideamethod,[Link] sameparameters,returnthesametype,[Link],youwillfindthatanyfunctiondesignedto workwithaninstanceofasuperclass,likeaDeck,willalsoworkwithinstancesofsubclasseslikeaHandorPokerHand. Ifyouviolatethisrule,yourcodewillcollapselike(sorry)ahouseofcards.

Glossary
encode: Torepresentonesetofvaluesusinganothersetofvaluesbyconstructingamappingbetweenthem. classattribute: [Link]. instanceattribute: Anattributeassociatedwithaninstanceofaclass.
[Link]/wiki/Think_Python/Print_version 194/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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:''
[Link]/wiki/Think_Python/Print_version 195/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

fourcardswiththesamerank ''straightflush:'' fivecardsinsequence(asdefinedabove)andwiththesamesuit Thegoaloftheseexercisesistoestimatetheprobabilityofdrawingthesevarioushands. Downloadthefollowingfilesfrom't h i n k p y t h o n . c o m / c o d e ':


C a r d . p y

: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 [Link].' '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 ' ',[Link] containanynumberofcards(although5and7arethemostcommonsizes).' 'Writeamethodnamed'''c l a s s i f y ''' thatfiguresout thehighestvalueclassificationforahandandsetsthe'''l a b e l '''[Link],a7cardhandmightcontainaflushandapairitshouldbe labeledflush.' 'Whenyouareconvincedthatyourclassificationmethodsare working,[Link]'''P o k e r H a n d . p y '''thatshufflesadeckofcards,dividesitintohands, classifiesthehands,andcountsthenumberoftimesvariousclassificationsappear.' 'Printatableoftheclassificationsandtheirprobabilities. [Link] 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

ThisexerciseusesTurtleWorldfromChapter'4'. [Link],see [Link]/wiki/Think_Python/Print_version

196/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

ThisexerciseusesTurtleWorldfromChapter'4'. [Link],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 '[Link] [Link]'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 [Link]'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,[Link]: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 [Link]:Turtleshaveanattribute,'w o r l d ',thatisareferencetotheTurtleWorldtheylivein,andtheTurtleWorldhasanattribute,'a n i m a l s ',thatisalistof allTurtlesintheworld. Modify's t e e r '[Link] 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 .
[Link]/wiki/Think_Python/Print_version 197/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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: [Link] [Link]: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 . [Link] [Link]:Aninfiniterecursioneventuallycausestheruntimeerrormaximum recursiondepthexceeded. [Link]:Anexpressionmay notbeevaluatedintheorderyouexpect,yieldinganincorrectresult. [Link],some techniquesareapplicableinmorethanonesituation.

Syntaxerrors
[Link],[Link] 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,[Link],ittellsyouwherePythonnoticedaproblem,whichisnot [Link],oftenontheprecedingline. Ifyouarebuildingtheprogramincrementally,[Link]. Ifyouarecopyingcodefromabook,[Link],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
[Link]/wiki/Think_Python/Print_version 198/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

quotationmarks. Ifyouhavemultilinestringswithtriplequotes(singleordouble),make [Link] i n v a l i dt o k e n errorattheendofyourprogram,oritmaytreatthefollowing [Link],itmightnotproduceanerrormessageatall!

Anunclosedopeningoperator( , { ,or
[ [Link],anerroroccursalmostimmediatelyinthenextline.

Checkfortheclassic = insteadof = = inside aconditional. Checktheindentationtomakesureitlinesupthewayit [Link],[Link] knowsaboutPythonandgeneratesconsistentindentation. Ifnothingworks,moveontothenextsection...

Ikeepmakingchangesanditmakesnodifference.
Iftheinterpretersaysthereisanerrorandyoudontseeit,[Link] programmingenvironmenttomakesurethattheprogramyouareeditingistheonePythonistryingtorun. Ifyouarenotsure,[Link] error,youarenotrunningthenewcode. Thereareafewlikelyculprits: Youeditedthefileandforgottosavethechangesbefore [Link],butsomedont. Youchangedthenameofthefile,butyouarestillrunning theoldname. Somethinginyourdevelopmentenvironmentisconfigured incorrectly.
[Link]/wiki/Think_Python/Print_version 199/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Ifyouarewritingamoduleandusing i m p o r t , makesureyoudontgiveyourmodulethesamenameasoneofthestandardPythonmodules.

Ifyouareusing i m p o r t toreadamodule,remember thatyouhavetorestarttheinterpreteroruse r e l o a d [Link],itdoesntdoanything. Ifyougetstuckandyoucantfigureoutwhatisgoingon,oneapproachistostartagainwithanewprogramlikeHello,World!,andmakesureyoucangeta [Link].

Runtimeerrors
Onceyourprogramissyntacticallycorrect,[Link]?

Myprogramdoesabsolutelynothing.
[Link] ifyouonlyplantoimportthismoduletosupplyclassesandfunctions. Ifitisnotintentional,makesurethatyouareinvokingafunctiontostartexecution,[Link] Executionsectionbelow.

Myprogramhangs.
Ifaprogramstopsandseemstobedoingnothing,[Link]. Ifthereisaparticularloopthatyoususpectisthe problem,adda p r i n t [Link] [Link],[Link]. Mostofthetime,aninfiniterecursionwillcausetheprogram torunforawhileandthenproduceaRuntimeError:[Link],[Link] youarenotgettingthiserrorbutyoususpectthereisaproblemwitharecursivemethodorfunction,youcanstillusethetechniquesintheInfiniteRecursion section. Ifneitherofthosestepsworks,starttestingother

[Link]/wiki/Think_Python/Print_version

200/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

loopsandotherrecursivefunctionsandmethods. Ifthatdoesntwork,thenitispossiblethat [Link]. InfiniteLoop Ifyouthinkyouhaveaninfiniteloopandyouthinkyouknowwhatloopiscausingtheproblem,adda p r i n t statementattheendoftheloopthatprintsthe valuesofthevariablesintheconditionandthevalueofthecondition. Forexample:


w h i l ex>0a n dy<0: #d os o m e t h i n gt ox #d os o m e t h i n gt oy p r i n t " x :" ,x p r i n t " y :" ,y p r i n t " c o n d i t i o n :" ,( x>0a n dy<0 )

Nowwhenyouruntheprogram,[Link],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,[Link],thereshould [Link],thenyouneedtorethinkthealgorithmand identifyabasecase. Ifthereisabasecasebuttheprogramdoesntseemtobereachingit,adda p r i n t statementatthebeginningofthefunctionormethodthatprintsthe [Link],youwillseeafewlinesofoutputeverytimethefunctionormethodisinvoked,andyouwillseetheparameters. Iftheparametersarenotmovingtowardthebasecase,youwillgetsomeideasaboutwhynot. FlowofExecution Ifyouarenotsurehowtheflowofexecutionismovingthroughyourprogram,add p r i n t statementstothebeginningofeachfunctionwithamessagelike enteringfunction f o o ,where f o o isthenameofthefunction. Nowwhenyouruntheprogram,itwillprintatraceofeachfunctionasitisinvoked.
[Link]/wiki/Think_Python/Print_version 201/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

WhenIruntheprogramIgetanexception.
Ifsomethinggoeswrongduringruntime,Pythonprintsamessagethatincludesthenameoftheexception,thelineoftheprogramwheretheproblem occurred,andatraceback. Thetracebackidentifiesthefunctionthatiscurrentlyrunning,andthenthefunctionthatinvokedit,andthenthefunctionthatinvoked that ,[Link] words,[Link] occurs. [Link] commonruntimeerrors: NameError: [Link] outsidethefunctionwheretheyaredefined. TypeError: Thereareseveralpossiblecauses: [Link]:indexing astring,list,ortuplewithsomethingotherthananinteger. Thereisamismatchbetweentheitemsinaformatstringand [Link]. Youarepassingthewrongnumberofargumentstoafunctionormethod. Formethods,lookatthemethoddefinitionandcheckthatthefirstparameteris s e l f .Thenlookatthemethodinvocationmakesureyouareinvoking themethodonanobjectwiththerighttypeandprovidingtheotherargumentscorrectly. KeyError: Youaretryingtoaccessanelementofadictionaryusingakeythatthedictionarydoesnotcontain. AttributeError: [Link]!Youcanuse d i r [Link] 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,[Link],adda p r i n t [Link]?Istheindextherightvalue?
[Link]/wiki/Think_Python/Print_version 202/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

ThePythondebugger(p d b )[Link] 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 [Link]:simplifytheoutputor simplifytheprogram. Tosimplifytheoutput,youcanremoveorcommentout p r i n t statementsthatarenthelping,orcombinethem,orformattheoutputsoitiseasierto understand. Tosimplifytheprogram,[Link],[Link],ifyouaresearchingalist, searcha [Link],giveitthesimplestinputthatcausestheproblem. Second,[Link],ifyoususpectthatthe problemisinadeeplynestedpartoftheprogram,[Link],trysplittingitintosmaller functionsandtestingthemseparately.

[Link],thatgivesyoua clueaboutwhatisgoingon. Similarly,[Link],anditdoes,thatcantipyou off.

Semanticerrors
Insomeways,semanticerrorsarethehardesttodebug,[Link] programissupposedtodo. [Link] [Link]. Youwilloftenwishthatyoucouldslowtheprogramdowntohumanspeed,[Link] p r i n t statementsisoftenshortcomparedtosettingupthedebugger,insertingandremovingbreakpoints,andsteppingtheprogramtowheretheerroris occurring.

Myprogramdoesntwork.
Youshouldaskyourselfthesequestions: Istheresomethingtheprogramwassupposedtodobut
[Link]/wiki/Think_Python/Print_version 203/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

whichdoesntseemtobehappening?Findthesectionofthecodethatperformsthatfunctionandmakesureitisexecutingwhenyouthinkitshould. Issomethinghappeningthatshouldnt?Findcodein yourprogramthatperformsthatfunctionandseeifitisexecutingwhenitshouldnt. Isasectionofcodeproducinganeffectthatisnot whatyouexpected?Makesurethatyouunderstandthecodeinquestion,especiallyifitinvolvesinvocationstofunctionsormethodsinotherPythonmodules. [Link]. Inordertoprogram,[Link],veryoftentheproblem isnotintheprogramitsinyourmentalmodel.

Thebestwaytocorrectyourmentalmodelistobreaktheprogramintoitscomponents(usuallythefunctionsandmethods)andtesteachcomponent [Link],youcansolvetheproblem. Ofcourse,[Link],thereshouldbeonlyasmallamountof newcodethatisnotknowntobecorrect.

A.3.2IvegotabighairyexpressionanditdoesntdowhatIexpect.

Writingcomplexexpressionsisfineaslongastheyarereadable,[Link] seriesofassignmentstotemporaryvariables. Forexample:


s e l f . h a n d s [ i ] . a d d C a r d ( s e l f . h a n d s [ s e l f . f i n d N e i g h b o r ( i ) ] . p o p C a r d ( ) )

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.

[Link]/wiki/Think_Python/Print_version

204/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link],ifyouaretranslatingthe expression x/2intoPython,youmightwrite:


y=x/2*m a t h . p i

[Link] x/2. Agoodwaytodebugexpressionsistoaddparenthesestomaketheorderofevaluationexplicit:


y=x/( 2*m a t h . p i )

Wheneveryouarenotsureoftheorderofevaluation,[Link](inthesenseofdoingwhatyouintended),itwill alsobemorereadableforotherpeoplewhohaventmemorizedtherulesofprecedence.

A.3.3IvegotafunctionormethodthatdoesntreturnwhatIexpect.

Ifyouhavea r e t u r n statementwithacomplexexpression,youdonthaveachancetoprintthe r e t u r n [Link],youcanuseatemporary [Link],insteadof:


r e t u r ns e l f . h a n d s [ i ] . r e m o v e M a t c h e s ( )

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,[Link],causingthesesymptoms: Frustrationandrage.
[Link]/wiki/Think_Python/Print_version 205/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Superstitiousbeliefs(thecomputerhatesme)and magicalthinking(theprogramonlyworkswhenIwearmyhatbackward). Randomwalkprogramming(theattempttoprogrambywriting everypossibleprogramandchoosingtheonethatdoestherightthing). Ifyoufindyourselfsufferingfromanyofthesesymptoms,[Link],[Link]?Whatare somepossiblecausesofthatbehavior?Whenwasthelasttimeyouhadaworkingprogram,andwhatdidyoudonext? [Link] bugsaretrains,showers,andinbed,justbeforeyoufallasleep.

No,Ireallyneedhelp.
[Link] justthething. Beforeyoubringsomeoneelsein,[Link],andyoushouldbeworkingonthesmallest [Link] p r i n t statementsintheappropriateplaces(andtheoutputtheyproduceshouldbecomprehensible).Youshould understandtheproblemwellenoughtodescribeitconcisely. Whenyoubringsomeoneintohelp,besuretogivethemtheinformationtheyneed: Ifthereisanerrormessage,whatisit andwhatpartoftheprogramdoesitindicate? Whatwasthelastthingyoudidbeforethiserroroccurred? Whatwerethelastlinesofcodethatyouwrote,orwhatisthenewtestcasethatfails? Whathaveyoutriedsofar,andwhathaveyoulearned? Whenyoufindthebug,[Link],youwillbeabletofind thebugmorequickly. Remember,[Link].

Answers
Chapter1
SeebelowforChapter1exercises.
[Link]/wiki/Think_Python/Print_version 206/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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'[Link]. 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
[Link]/wiki/Think_Python/Print_version 207/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Sopythonisassumingyouwanttoconvertanoctalnumbertoadecimalnumber.Inthebase8numberingsystemwherevalidnumbersare 0,1,2,3,4,5,6 and7.


B a s e 8 :0 00 10 20 30 40 50 60 71 01 11 21 31 41 51 61 72 02 12 22 32 4 B a s e1 0 :0 00 10 20 30 40 50 60 70 80 91 01 11 21 31 41 51 61 71 81 92 0

[Link]'ones'.Theonetotherightofthatisatallyof thenumberof'eights',theonenexttothatisatallyofafullcolumnof'eight'timesthe'eightcolumn'64.Theonenexttothatis64*[Link] moreinformationread[BaseEightmath([Link] Thatiswhy zipcode=[Link]:


> > >p r i n t0 2 1 3 2 1 1 1 4 > > >( 2 * 5 1 2 ) + ( 1 * 6 4 ) + ( 3 * 8 ) + ( 2 * 1 ) 1 1 1 4 > > >

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%[Link]$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
[Link]/wiki/Think_Python/Print_version 208/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

$ 0 . 7 5 D e l i v e r yc o s tf o re x t r ab o o k s $ 4 4 . 2 5 T o t a lc o s tf o re x t r ab o o k s $ 4 7 . 2 5 T o t a lD e l i v e r yc o s t $ 9 4 5 . 4 5 T o t a lB i l l T h i sa n s w e ri sw r o n gb e c a u s e4 0 . 0 / 1 0 0 . 0r e t u r nw r o n gv a l u e0 . 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2f o rm o r ei n f os e eI E E E7 5 4( S t a n d a r df o rF l o a t i n g P o i n tA r i t h m e t i c ) > > >( 2 4 . 9 5 2 4 . 9 5 * 4 0 . 0 / 1 0 0 . 0 ) * 6 0 + 3 + 0 . 7 5 * ( 6 0 1 ) 9 4 5 . 4 4 9 9 9 9 9 9 9 9 9 9 9 3 > > >2 4 . 9 5 * 0 . 6 * 6 0 + 0 . 7 5 * ( 6 0 1 ) + 3 9 4 5 . 4 5

IfIleavemyhouseat6:52amandrun1mileataneasypace(8:15permile),then3milesattempo(7:12permile)and1mileateasypaceagain,whattime doIgethomeforbreakfast? Answer: 7:30am HowIdidit:


> > >s t a r t=( 6 * 6 0 + 5 2 ) * 6 0 > > >e a s y=( 8 * 6 0 + 1 5 ) * 2 > > >f a s t=( 7 * 6 0 + 1 2 ) * 3 > > >f i n i s h _ h o u r=( s t a r t+e a s y+f a s t ) / ( 6 0 * 6 0 . 0 ) > > >f i n i s h _ f l o o r e d=( s t a r t+e a s y+f a s t ) / ( 6 0 * 6 0 ) # i n t ( )f u n c t i o nc a na l s ob eu s e dt og e ti n t e g e rv a l u e ,b u ti s n ' tt a u g h ty e t . > > >f i n i s h _ m i n u t e =( f i n i s h _ h o u r-f i n i s h _ f l o o r e d ) * 6 0 > > >p r i n t' F i n i s ht i m ew a s% d : % d '%( f i n i s h _ h o u r , f i n i s h _ m i n u t e ) F i n i s ht i m ew a s7 : 3 0 > > >

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
[Link]/wiki/Think_Python/Print_version 209/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Youcanseemysolutionat[[Link]
" " " 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 ( ) :
[Link]/wiki/Think_Python/Print_version 210/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

p r i n t' + + + ' d e fp r i n t _ r o w ( ) : p r i n t' | | | '

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 )
[Link]/wiki/Think_Python/Print_version 211/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 [Link],thecumulativesumof[1,2,3]is[1,3,6].
[Link]/wiki/Think_Python/Print_version 212/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

d e fc u m u l a t i v e ( a ) : c u m u l a t i v e=[ ] s u m=0 f o rii na : s u m+ =i c u m u l a t i v e . a p p e n d ( s u m ) r e t u r nc u m u l a t i v e a=[ 1 ,2 ,3 ] p r i n t ( c u m u l a t i v e ( a ) )

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
[Link] operatorasafastwaytocheckwhetherastringisinthedictionary.
e n g l i s h d i c t i o n a r y=d i c t ( )
[Link]/wiki/Think_Python/Print_version 213/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

f i n=o p e n ( ' w o r d s . t x t ' ) l i n e=f i n . r e a d l i n e ( ) d e fe n g d i c d e f i n e ( ) : i n d e x=0 w h i l ei n d e x< =1 0 0 0 : w o r d=l i n e . s t r i p ( ) e n g l i s h d i c t i o n a r y [ w o r d ]=i n d e x i n d e x+ =1 r e t u r ne n g l i s h d i c t i o n a r y

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
[Link]/wiki/Think_Python/Print_version 214/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

n u m b e r s=( 1 , 2 , 3 ) d e fs u m a l l ( n u m b e r s ) : x=0 f o rii nn u m b e r s : x=x+i p r i n tx s u m a l l ( n u m b e r s )

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
[Link]/wiki/Think_Python/Print_version 215/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )
[Link]/wiki/Think_Python/Print_version 216/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 ) :
[Link]/wiki/Think_Python/Print_version 217/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )
[Link]/wiki/Think_Python/Print_version 218/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 219/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

d e fp r i n t _ t i m e ( t ) : #0i saf i l lc h a r a c t e r ,2d e f i n e st h ew i d t h p r i n t ( ' { } : { : 0 2 } : { : 0 2 } ' . f o r m a t ( t . h o u r ,t . m i n u t e ,t . s e c o n d ) )

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 ) :
[Link]/wiki/Think_Python/Print_version 220/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 221/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 fm u l _ t i m e ( t i m e ,f a c t o r ) : s e c o n d s=t i m e _ t o _ i n t ( t i m e ) s e c o n d s* =f a c t o r s e c o n d s=i n t ( s e c o n d s ) r e t u r ni n t _ t o _ t i m e ( s e c o n d s ) d e fa v e r a g e _ p a c e ( t i m e ,d i s t a n c e ) : r e t u r nm u l _ t i m e ( t i m e ,1 / d i s t a n c e )

Exercise16.7
WriteaclassdefinitionforaDateobjectthathasattributes day, monthand [Link] increment_datethattakesaDateobject, date,andan integer, n,andreturnsanewDateobjectthatrepresentstheday ndaysafter [Link]:ThirtydayshathSeptember...Challenge:doesyourfunctiondeal withleapyearscorrectly?See [Link]/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
[Link]/wiki/Think_Python/Print_version 222/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link] 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 ( ) :
[Link]/wiki/Think_Python/Print_version 223/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 ( )

[Link],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
[Link]/wiki/Think_Python/Print_version 224/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )

[Link]://[Link]/code/color_list.pyandusethefunction read_colorstogeneratealistoftheavailablecolorsonyoursystem,theirnames [Link].


#A st h e r ec u r r e n t l y( 2 0 1 3 0 4 1 2 )i sn of u n c t i o nr e a d _ c o l o r si nc o l o r _ l i s t . p y #Iu s eaw o r k a r o u n da n ds i m p l yi m p o r tt h ev a r i a b l eC O L O R Sf r o mc o l o r _ l i s t . p y . #It h e nu s et h ef u n c t i o na l l _ c o l o r s ( )o nC O L O R St og e tal i s to ft h ec o l o r s . f r o mc o l o r _ l i s ti m p o r tC O L O R S f r o mv i s u a li m p o r ts c e n e ,s p h e r e d e fa l l _ c o l o r s ( c o l o r s _ s t r i n g = C O L O R S ) : " " " E x t r a c tal i s to fu n i q u eR G B t u p l e sf r o mC O L O R S . T h et u p l e sl o o kl i k e( r ,g ,b ) ,w h e r er ,ga n dba r ee a c hi n t e g e r si n [ 0 ,2 5 5 ] . " " " #s p l i tt h es t r i n gi n t ol i n e sa n dr e m o v ei r r e l e v a n tl i n e s l i n e s=c o l o r s _ s t r i n g . s p l i t ( ' \ n ' ) [ 2 : 2 ] #s p l i tt h ei n d i v i d u a ll i n e sa n dr e m o v et h en a m e s n u m b e r s _ o n l y=[ l i n e . s p l i t ( ) [ : 3 ]f o rl i n ei nl i n e s ] #t u r ns t r i n g si n t oi n t sa n dr g b l i s t si n t ot u p l e s r g b _ t u p l e s=[ t u p l e ( [ i n t ( s )f o rsi nl s t ] )f o rl s ti nn u m b e r s _ o n l y ] #r e t u r nal i s to fu n i q u et u p l e s r e t u r nl i s t ( s e t ( r g b _ t u p l e s ) ) d e fm a k e _ s p h e r e s ( c o l o r _ t u p l e s = a l l _ c o l o r s ( ) ) : 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 ) f o r( r ,g ,b )i nc o l o r _ t u p l e s : s p h e r e ( p o s = ( r ,g ,b ) ,r a d i u s = 7 ,c o l o r = ( r / 2 5 5 . ,g / 2 5 5 . ,b / 2 5 5 . ) ) i f_ _ n a m e _ _= =' _ _ m a i n _ _ ' : m a k e _ s p h e r e s ( )

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
[Link]/wiki/Think_Python/Print_version 225/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 ) :
[Link]/wiki/Think_Python/Print_version 226/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

i ff i r s t ( w o r d ) = = l a s t ( w o r d ) : w o r d=m i d d l e ( w o r d ) n = l e n ( w o r d ) i fn < 2 : p r i n t" p a l i n d r o m e " e l s e : r e t u r np a l i n d r o m e ( w o r d ) e l s e : p r i n t" n o tp a l i n d r o m e " w o r d = r a w _ i n p u t ( " E n t e rt h e s t r i n g : " ) p a l i n d r o m e ( w o r d )

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
[Link]/wiki/Think_Python/Print_version 227/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )
[Link]/wiki/Think_Python/Print_version 228/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 :
[Link]/wiki/Think_Python/Print_version 229/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 230/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 )
[Link]/wiki/Think_Python/Print_version 231/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

i fh a n d . c l a s s i f y ( )= =c o n f i g : s u c c e s s e s+ =1 r e t u r n1 . 0 * s u c c e s s e s / t r i a l s # I t e r a t eu n t i lf i r s td e s i r e dc o n f i g . : i f_ _ n a m e _ _= =' _ _ m a i n _ _ ' : c=1 w h i l eT r u e : d e c k=D e c k ( ) d e c k . s h u f f l e ( ) h a n d=P o k e r H a n d ( ' P o k e rH a n d% d '%c ) d e c k . m o v e _ c a r d s ( h a n d ,5 ) p r i n th a n d p r i n th a n d . S F L ( ) i fh a n d . S F L ( ) : p r i n th a n d . S T R s e q ( ) b r e a k p r i n t' ' c+ =1 C o d eb yV i c t o rA l v a r e z

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
[Link]/wiki/Think_Python/Print_version 232/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version

event,19.1
233/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

sum,10.7

for,4.2,8.3,10.3

infinite,7.3,19.1,A.2.2 addmethod,17.7 nested,18.4 additionwithcarrying,7.6 traversal,8.3 algorithm,1.2,1.7,7.6,13.7 while,7.3 Euclid,6.11

MD5,14.12

looping withdictionaries,11.2

RSA,11.7 withindices,9.4 squareroot,7.9 withstrings,8.7

aliasing,10.10,10.11,10.14,15.2,15.6,17.12 loopingandcounting,8.7 copyingtoavoid,10.13 loopingwithindices,10.3


[Link]/wiki/Think_Python/Print_version 234/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

[Link]/wiki/Think_Python/Print_version

235/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

membership argumentscatter,12.4 bisectionsearch,10.15

arithmeticoperator,2.5

dictionary,11

assertstatement,16.5

list,10.2

assignment,2.11,7.1,10.1

set,11

item,8.5,10.2,12.1 memo,11.5,11.9 multiple,7.8,11.6 mentalmodel,A.3.1 tuple,12.2,12.3,12.5,12.10 metaphor,methodinvocation,17.2


[Link]/wiki/Think_Python/Print_version 236/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

assignmentstatement,2.2

metathesis,12.11

attribute __dict__,17.10

method,8.8,8.12,17.1,17.11

__cmp__,18.3 class,18.2,18.10 __str__,17.6,18.5 initializing,17.10 add,17.7 instance,15.2,15.8,18.2,18.10 append,10.6,10.12,18.4,18.6

availablecolors,15.9,17.12

close,14.2,14.6,14.8

config,19.3 Bacon,Kevin,14.12 count,8.8 Bangladesh,nationalflag,15.9 extend,10.6 Buttonwidget,19.2 get,11.1 basecase,5.9,5.13


[Link]/wiki/Think_Python/Print_version 237/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 238/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version

methodsyntax,17.2
239/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

[Link]/wiki/Think_Python/Print_version

240/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version

urllib,14.12,19.11
241/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 242/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

parent,18.7 mutableobject,asdefaultvalue,17.12 Rectangle,15.3

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

[Link]/wiki/Think_Python/Print_version

243/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

Event,19.8 comparisonoperator,5.2 embedded,15.3,15.8,17.12 compile,1.1,1.7 file,9.1,9.6 composition,3.4,3.8,3.14,6.3,18.4 function,3.5,3.15 compoundstatement,5.4,5.13


[Link]/wiki/Think_Python/Print_version 244/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

module,14.9 compression file,14.8 mutable,15.5

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

[Link]/wiki/Think_Python/Print_version

245/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

del,10.8 pixel,19.8 format,14.3,14.11,A.2.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
[Link]/wiki/Think_Python/Print_version 246/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

shallow,15.6 modulus,5.1,5.13 slice,8.4,10.5 not,5.3 toavoidaliasing,10.13 or,5.3

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

countingandlooping,8.7 operatoroverloading,17.7,18.3 crosswords,9.1 operator,arithmetic,2.5 cummings,e.e.,1.3.1 option,19.2,19.10 cumulativesum,10.7 optionalargument,8.8,10.9,11.3


[Link]/wiki/Think_Python/Print_version 247/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

[Link]/wiki/Think_Python/Print_version

248/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version

other,17.4
249/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

defkeyword,3.5

self,17.2

defaultvalue,13.5,13.11,17.5 parentclass,18.7,18.7,18.10 avoidingmutable,17.12 parentheses argumentin,3.1 definition circular,6.5 empty,3.5,8.8

class,15.1

matching,1.3.1

function,3.5

overridingprecedence,2.7

recursive,12.11

parametersin,3.8,3.9

parentclassin,18.7 deloperator,10.8 tuplesin,12.1 deletion,elementoflist,10.8

delimiter,10.9,10.14
[Link]/wiki/Think_Python/Print_version

parse,1.4,1.7,14.12
250/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

planned,16.4 pattern problemrecognition,9.3,9.4 DSU,12.7,13.4

prototypeandpatch,16.2,16.4

decoratesortundecorate,12.7

randomwalkprogramming,13.10,A.3.4

filter,10.7,10.14

guardian,6.8,6.10,8.11 diagram callgraph,11.9 map,10.7,10.14

class,18.8,18.10

reduce,10.7,10.14

[Link]/wiki/Think_Python/Print_version

251/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

[Link]/wiki/Think_Python/Print_version

252/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

subtraction,13.6

plaintext,9.1,13.1,14.12,19.11

traversal,12.6,17.10

planneddevelopment,16.4,16.6

playingcard,AngloAmerican,18 dictionarymethods anydbmmodule,14.6 poetry,1.4

point,mathematical,15.1 directory,14.4,14.11 poker,18,18.11 walk,14.4 polygonfunction,4.3 working,14.4 polymorphism,17.9,17.11,18.9

dispatch typebased,17.9

popmethod,10.8,18.6

popenfunction,14.8 dispatch,typebased,17.8 portability,1.1,1.7 divisibility,5.1 postcondition,4.10,6.9,18.9


[Link]/wiki/Think_Python/Print_version 253/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

division floatingpoint,2.5

pprintmodule,11.8

precedence,2.11,A.3.2 floor,2.5,5.12 precondition,4.10,4.11,4.11,6.9,10.15,18.9

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
[Link]/wiki/Think_Python/Print_version 254/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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 [Link],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

[Link]/wiki/Think_Python/Print_version

255/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 256/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

equivalence,10.10 rank,18.1 equivalent,10.14 raw_inputfunction,5.11 error compiletime,A readmethod,14.8

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
[Link]/wiki/Think_Python/Print_version

redundancy,1.4
257/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

[Link]/wiki/Think_Python/Print_version

258/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

UnboundLocalError,11.6 reverselookup,dictionary,11.3,11.9 ValueError,5.11,11.3,12.2 reversewordpair,10.15

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

[Link]/wiki/Think_Python/Print_version

259/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

Scrabble,12.11 extendmethod,10.6 SimpleTurtleWorldclass,19.6

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
[Link]/wiki/Think_Python/Print_version 260/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 261/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 262/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

frame,3.10,3.14,5.9,6.5,11.5 sinefunction,3.3 frequency,11.1 singleton,11.4,11.9,12.1 letter,12.11 slice,8.12 word,13.1,13.12 copy,8.4,10.5

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

ack,6.11 sliceoperator,8.4,8.13,10.5,10.12,12.1 arc,4.3 sortmethod,10.6,10.13,12.7,18.6 choice,13.2 sortedfunction,12.8


[Link]/wiki/Think_Python/Print_version 263/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

circle,4.3 sourcecode,1.1,1.7 cmp,18.3 specialcase,9.5,9.6,16.3 compare,6.1 specialvalue deepcopy,15.6 False,5.2

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
[Link]/wiki/Think_Python/Print_version 264/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

[Link]/wiki/Think_Python/Print_version

265/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

repr,14.10 stepsize,8.13 reversed,12.8 strfunction,3.2 shuffle,18.6 __str__method,17.6,18.5 sorted,12.8 string,2.1,2.11,10.9,12.8 sqrt,3.3,6.2


[Link]/wiki/Think_Python/Print_version 266/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

functiondefinition,3.5,3.6,3.14,3.14 stringmethod,8.13 functionframe,3.10,3.14,5.9,11.5 stringmodule,13.1 functionobject,3.5,3.15


[Link]/wiki/Think_Python/Print_version 267/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

stringrepresentation,14.10,17.6 functionparameter,3.8 stringtype,2.1 functionsyntax,17.2 stripmethod,9.1,13.1 functiontype modifier,16.3 structshapemodule,12.9

pure,16.2

structure,1.4

subclass,18.7 function,fruitful,3.11 subject,17.2,17.11,19.6 function,math,3.3 subtraction function,reasonsfor,3.12 dictionary,13.6

function,trigonometric,3.3

withborrowing,7.6

function,tupleasreturnvalue,12.3 subtractionwithborrowing,16.4 function,void,3.11 suffix,13.8


[Link]/wiki/Think_Python/Print_version 268/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

generalization,4.5,4.11,9.3,16.4 Tagger,18.11 geometrymanager,19.6,19.10 Textwidget,19.5 getmethod,11.1 Timeclass,16.1 getattrfunction,17.10


[Link]/wiki/Think_Python/Print_version 269/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

Tkinter,19.1 getcwdfunction,14.4 Truespecialvalue,5.2 globalstatement,11.6 Turingcompletelanguage,6.5 globalvariable,11.6,11.9 TuringThesis,6.5 update,11.6 Turing,Alan,6.5

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

[Link]/wiki/Think_Python/Print_version

270/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

hasattrfunction,15.7,17.10 text hashfunction,11.4,11.9 plain,9.1,13.1,14.12,19.11

hashable,11.4,11.9,12.6

random,13.8

hashtable,11,11.9 textfile,14.11 header,3.5,3.14,A.1 token,1.4,1.7 helputility,1.8 traceback,3.10,3.14,5.10,5.12,11.3,A.2.3 hexadecimal,15.1


[Link]/wiki/Think_Python/Print_version 271/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

translatemethod,13.1 highlevellanguage,1.1,1.7 traversal,8.3,8.3,8.6,8.11,8.12,9.3,9.3,10.7,10.14, 11.1,11.2,12.5,12.5,12.7,13.3

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

[Link]/wiki/Think_Python/Print_version

272/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version 273/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

inheritance,18.7,18.10 typechecking,6.8 initmethod,17.5,17.10,18.1,18.4,18.7


[Link]/wiki/Think_Python/Print_version 274/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

typeconversion,3.2 initialization(beforeupdate),7.2 typefunction,15.7 instance,4.1,4.11,15.1,15.8 typebaseddispatch,17.8,17.9,17.11 asargument,15.2 typewriter,turtle,4.12 asreturnvalue,15.4 typographicalerror,13.10

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

integer,2.11 ls,14.8 long,11.7

URL,14.12,19.11

[Link]/wiki/Think_Python/Print_version

275/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

item,8.12,10.1 updatemethod,12.6 Canvas,19.3,19.10 updateoperator,10.7 dictionary,11.9


[Link]/wiki/Think_Python/Print_version 276/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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

default,13.5 Kangarooclass,17.12 tuple,12.3 KevinBaconGame,14.12 valuesmethod,11 KeyError,11,A.2.3 variable,2.2,2.11 Kochcurve,5.14 global,11.6


[Link]/wiki/Think_Python/Print_version 277/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

key,11,11.9 local,3.9 keyvaluepair,11,11.9,12.6 temporary,6.1,6.10,A.3.2 keyboardinput,5.11 updating,7.2 keysmethod,11.2

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

voidmethod,10.6 keywordargument,4.5,4.11,12.7,19.2,19.10 vpythonmodule,17.12

Labelwidget,19.2 Worldmodule,15.9 Linux,1.3.4


[Link]/wiki/Think_Python/Print_version 278/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

walk,directory,14.4 language formal,1.4 whileloop,7.3

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

Label,19.2 leapoffaith,6.6 Menubutton,19.7 lenfunction,3.15,8.2,11 Text,19.5 letterfrequency,12.11

[Link]/wiki/Think_Python/Print_version

279/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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
[Link]/wiki/Think_Python/Print_version

usewithdict,12.6
280/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

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"[Link]
Thispagewaslastmodifiedon23October2013,at21:16. TextisavailableundertheCreativeCommonsAttribution/[Link],youagreetotheTermsof UseandPrivacyPolicy.
[Link]/wiki/Think_Python/Print_version 281/282

10/24/13

Think Python/Print version - Wikibooks, open books for an open world

[Link]/wiki/Think_Python/Print_version

282/282

Common questions

Powered by AI

Using functions improves code readability and manageability by allowing programmers to encapsulate sequences of statements into single, reusable units, making it easier to read and debug programs . Functions eliminate repetitive code, which reduces the size of the program and centralizes code changes, thus simplifying maintenance . They provide clear interfaces that describe how to use them, making collaboration and code sharing more efficient . Moreover, functions facilitate a modular development approach, enabling programmers to focus on smaller, manageable parts of a program before assembling them into a whole .

The search pattern in Python enables problem-solving by providing a systematic way to iterate over sequences to find or check elements, facilitating solutions to exercises like checking for forbidden or required characters in words. By using loops and conditionals, it allows programmers to efficiently determine characteristics of strings and lists, helping in tasks such as verifying the absence of certain letters, or confirming the presence of required attributes .

Syntax errors occur when Python cannot translate the source code into byte code due to incorrect syntax, producing a syntax error message. Runtime errors happen when an error occurs during the execution of a program, often identifiable by where in the program it occurred and the context function. Semantic errors, in contrast, appear when a program runs without producing error messages but doesn't perform the intended task, meaning the logic of the code is flawed even if technically correct according to syntax .

Operator overloading enables custom classes in Python to define or modify the behavior of operators, like '+', making them intuitive to use with the class’ objects. By creating special methods such as '__add__', these classes can support operations consistent with the type of data they model. This capacity to handle user-defined types with familiar syntax facilitates clearer, more readable code, reflecting operations naturally associated with those types .

Debugging is considered intellectually rich and challenging because it involves detective work and experimental science. Programmers must analyze clues and infer the processes that led to errors, akin to solving a mystery. The process requires the development and testing of hypotheses about what might be going wrong, iterating solutions, and refining understanding of the code. This makes debugging both a critical and stimulating aspect of programming, where eliminating the impossible variables often leads to the solution, drawing from ideas similar to those espoused by Sherlock Holmes .

Maintaining code consistency with respect to indentation in Python is crucial because Python uses indentation to define the blocks of code. Each block must be consistently indented both for readability and to avoid syntax errors. Unlike other languages that use braces or keywords to define blocks, Python relies entirely on indentation to determine the structure of the code. Thus, mismatched or inconsistent indentation can lead to syntax errors, causing the program to fail to execute properly or even compile . Indentation errors may manifest as syntax errors, which are disruptive and need correcting before the program can run successfully . Thus, clear and consistent indentation is not just a matter of style in Python; it’s a requirement for functional code.

Bisection search improves efficiency by leveraging the ordered nature of a sorted list to halve the search space each time it's compared, taking logarithmic steps proportional to the size of the list, rather than the linear steps required in a direct linear search, where each element is checked sequentially. This method reduces the number of comparisons dramatically, allowing a very quick conclusion on the presence or absence of an element .

The '__init__' method in object-oriented programming, often referred to as the initializer, is a special method that automatically executes when a new instance of a class is created. It is used to set initial values for the object's attributes, ensuring that all objects are properly initialized with the necessary data upon creation . The '__str__' method, on the other hand, is another special method used to define how an instance of a class should be represented as a string. It is typically implemented to provide a human-readable string output, which is especially useful when printing objects or for debugging purposes, allowing an object to be passed to the 'print()' function or be converted to a string using 'str()' .

Operator overloading combined with method binding in class-based implementations, like with Time objects, provides enhanced functionality by allowing intuitive arithmetic or logical operations directly on objects, like adding times, without cumbersome methods. This enables code to read naturally, similarly to sentence structure, improving readability. Overloading methods like '__add__' and using binding for specific logic keeps operations encapsulated and tied logically to the object’s domain, promoting clear, maintainable code .

A function in Python might return 'None' when it does not explicitly return a value, or when its execution path ends without hitting a return statement. In Python, all functions return 'None' implicitly if no return statement is executed . This behavior is significant for error handling and program flow because it allows functions to signal that no result is available, or that an expected operation did not occur, such as in cases of insufficient conditions met in the function logic. For instance, if a function lacks a return statement in certain branches, it can indirectly indicate that the logic path was not anticipated or handled, which can be useful for debugging and control flow .

You might also like