1.1
1.2
1.3
1.4
1.5
1.6
1.7
1.8
1.9
1.10
1.11
1.12
1.13
1.14
1.15
1.16
1.17
1.18
1.19
1.20
1.21
1.22
1.23
1.24
1.25
TableofContentsIntroduction
Dedication
Preface
AboutPython
Installation
FirstSteps
Basics
OperatorsandExpressions
Controlflow
Functions
Modules
DataStructures
ProblemSolving
ObjectOrientedProgramming
InputandOutput
Exceptions
StandardLibrary
More
WhatNext
Appendix:FLOSS
Appendix:About
Appendix:RevisionHistory
Appendix:Translations
Appendix:TranslationHow-to
Feedback
1
AByteofPython"AByteofPython"isafreebookonprogrammingusingthePythonlanguage.ItservesasatutorialorguidetothePythonlanguageforabeginneraudience.Ifallyouknowaboutcomputersishowtosavetextfiles,thenthisisthebookforyou.
ForPythonversion3
ThisbookwillteachyoutousePythonversion3.TherewillalsobeguidanceforyoutoadapttotheolderandmorecommonPythonversion2inthebook.
WhoreadsAByteofPython?
Herearewhatpeoplearesayingaboutthebook:
Somewherearound2004-05whenIwasconvincedIwasn’tsmartenoughtobeaprogrammer,IcamecameacrosstheoriginalAByteof#Python,andthatchangedmyentireperspectiveoncomputingandlife,[email protected],2020
Thisisthebookthatgotmeintoprogrammingalmostadecadeago.Thankyou@swaroopch.Youchangedmylife.--StefanFroelichonAug2,2019
Iamwritingthisemailtothankyouforthegreathelpyourbookhasdoneforme!ItwasareallygoodbookthatIenjoyedthoroughly.Asa15yearoldwhohasneverdoneprogrammingbefore,tryingtolearnPythononlinewasdifficultandIcouldn'tunderstandanything.ButIfeltlikeyourbookgavewasmucheasiertounderstandandeasedmeintothewholenewworldofprogramming.Thankstoyou,Icannowwriteahighlevellanguagewithease.Ithoughtprogrammingwouldbehardandboring,butwithyourbook'shelp,Irealisedhowfunandinterestingyetsimpleitcanbe!Iwouldliketothankyouagainforyourhardworkonhelpingoutbeginnerslikeme.--ProttyashitaTahiyatonSep17,2019
Thisisthebestbeginner'stutorialI'veeverseen!Thankyouforyoureffort.--WaltMichalik
Thebestthingifoundwas"AByteofPython",whichissimplyabrilliantbookforabeginner.It'swellwritten,theconceptsarewellexplainedwithselfevidentexamples.--JoshuaRobin
Excellentgentleintroductiontoprogramming#Pythonforbeginners--ShanRajasekaran
starttolovepythonwitheverysinglepageread--HerbertFeutl
perfectbeginnersguideforpython,willgiveukeytounlockmagicalworldofpython--Dilip
Ishouldbedoingmyactual"work"butjustfound"AByteofPython".Agreatguidewithgreatexamples.--BiologistJohn
RecentlystartedreadingaByteofpython.Awesomework.Andthattooforfree.Highlyrecommendedforaspiringpythonistas.--Mangesh
AByteofPython,writtenbySwaroop.(thisisthebookI'mcurrentlyreading).Probablythebesttostartwith,andprobablythebestintheworldforeverynewbieorevenamoreexperienceduser.--Apostolos
EnjoyingReading#ByteOfPythonby@swaroopchbestbookever--YuvrajSharma
AByteofPythonby@swaroopchisstillthe"Bestnewbieguidetopython"--NicksonKaigi
Introduction
2
ThankyousomuchforwritingAByteOfPython.IjuststartedlearninghowtocodetwodaysagoandI'malreadybuildingsomesimplegames.YourguidehasbeenadreamandIjustwantedtoletyouknowhowvaluableithasbeen.--Franklin
I'mfromDayanandasagarCollegeofEngineering(7thsem,CSE).Firstlyiwanttosaythatyourbook"Thebyteofpython"istoogoodabookforabeginnerinpythonlikeme.Theconceptsaresowellexplainedwithsimpleexamplesthathelpedmetoeasilylearnpython.Thankyousomuch.--Madhura
Iama18yearoldITstudentstudyingatUniversityinIreland.Iwouldliketoexpressmygratitudetoyouforwritingyourbook"AByteofPython",Ialreadyhadknowledgeof3programminglangagues-C,JavaandJavascript,andPythonwasbyfartheeasiestlangagueIhaveeverlearned,andthatwasmainlybecauseyourbookwasfantasticandmadelearningpythonverysimpleandinteresting.ItisoneofthebestwrittenandeasytofollowprogrammingbooksIhaveeverread.Congratulationsandkeepupthegreatwork.--Matt
Hi,I'mfromDominicanRepublic.MynameisPavel,recentlyIreadyourbookAByteofPythonandIconsideritexcellent!!:).Ilearntmuchfromalltheexamples.Yourbookisofgreathelpfornewbieslikeme...--PavelSimo
IamastudentfromChina,Now,IhavereadyoubookAbyteofPython,Ohit'sbeautiful.Thebookisverysimplebutcanhelpallthefirstlearnners.YouknowIaminterestinginJavaandcloudcomputingmanytimes,ihavetocodingprogrammfortheserver,soithinkpythonisagoodchoice,finishyourbook,ithinkitsnotonlyagoodchoiceitsmustusethePython.MyEnglishisnotverywell,theemailtoyou,ijustwannathankyou!BestWishesforyouandyourfamily.--RoyLau
IrecentlyfinishedreadingByteofPython,andIthoughtIreallyoughttothankyou.IwasverysadtoreachthefinalpagesasInowhavetogobacktodull,tediousoreillyoretc.manualsforlearningaboutpython.Anyway,Ireallyappreciateyourbook.SamuelYoung
DearSwaroop,Iamtakingaclassfromaninstructorthathasnointerestinteaching.WeareusingLearningPython,secondedition,byO'Reilly.Itisnotatextforbeginnerwithoutanyprogrammingknowledge,andaninstructorthatshouldbeworkinginanotherfield.Thankyouverymuchforyourbook,withoutitIwouldbecluelessaboutPythonandprogramming.Thanksamillion,youareabletobreakthemessagedowntoalevelthatbeginnerscanunderstandandnoteveryonecan.--JosephDuarte
Iloveyourbook!ItisthegreatestPythontutorialever,andaveryusefulreference.Brilliant,atruemasterpiece!Keepupthegoodwork!--Chris-AndréSommerseth
Firstofall,Iwanttosaythankstoyouforthisgreatebook.Ithinkitisagoodbookforthosewhoarelookingforabeginner'stutorialforPython.Itisabouttwoorthereyearsago,Ithink,whenIfirstheardofthisbook.Atthattime,IamnotabletoreadsomebookinEnglishyet,soIgotachinesetranslation,whichtookmeintothegateofPythonprogramming.Recently,Irereadthisbook.Thistime,ofcourse,theenglishversion.Icouldn'tbelievethatIcanreadthewholebookwithoutmydictionaryathand.Ofcourse,itallduestoyourefforttomakethisbookaneasy-to-understandone.--myd7349
I'mjuste-mailingyoutothankyouforwritingByteofPythononline.IhadbeenattemptingPythonforafewmonthspriortostumblingacrossyourbook,andalthoughImadelimitedsuccesswithpyGame,Inevercompletedaprogram.Thankstoyoursimplificationofthecategories,Pythonactuallyseemsareachablegoal.ItseemslikeIhavefinallylearnedthefoundationsandIcancontinueintomyrealgoal,gamedevelopment....Onceagain,thanksVERYmuchforplacingsuchastructuredandhelpfulguidetobasicprogrammingontheweb.ItshovedmeintoandoutofOOPwithanunderstandingwheretwotextbookshadfailed.--MattGallivan
IwouldliketothankyouforyourbookAByteofPythonwhichimyselffindthebestwaytolearnpython.Iama15yearoldiliveinegyptmynameisAhmed.Pythonwasmysecondprogramminglanguageilearnvisualbasic6atschoolbutdidn'tenjoyit,howeverireallyenjoyedlearningpython.Imadetheaddressbookprogramandiwassucessful.iwilltrytostartmakemoreprogramsandreadpythonprograms(ifyoucouldtellmesourcethatwouldbehelpful).Iwillalsostartonlearningjavaandifyoucantellmewheretofindatutorialasgoodasyoursforjavathatwouldhelpmealot.Thanx.--AhmedMohammed
Introduction
3
AwonderfulresourceforbeginnerswantingtolearnmoreaboutPythonisthe110-pagePDFtutorialAByteofPythonbySwaroopCH.Itiswell-written,easytofollow,andmaybethebestintroductiontoPythonprogrammingavailable.--DrewAmes
YesterdayIgotthroughmostofByteofPythononmyNokiaN800andit'stheeasiestandmostconciseintroductiontoPythonIhaveyetencountered.HighlyrecommendedasastartingpointforlearningPython.--JasonDelport
ByteofVimandPythonby@swaroopchisbyfarthebestworksintechnicalwritingtome.Excellentreads#FeelGoodFactor--Surendran
"Byteofpython"bestonebyfarman(inresponsetothequestion"Cananyonesuggestagood,inexpensiveresourceforlearningthebasicsofPython?")--JustinLoveTrue
TheBookByteofpythonwasveryhelpful..Thanksbigtime:)Chinmay
AlwaysbeenafanofAByteofPython-madeforbothnewandexperiencedprogrammers.--PatrickHarrington
Istartedlearningpythonfewdaysagofromyourbook..thanksforsuchanicebook.itissowellwritten,youmademylifeeasy..soyoufoundanewfanofyours..thatsme:)tonsofthanks.--GadadhariBheem
BeforeIstartedtolearnPython,I'veacquiredbasicprogrammingskillsinAssembly,C,C++,C#andJava.TheveryreasonIwantedtolearnPythonisit'spopular(peoplearetalkingaboutit)andpowerful(reality).ThisbookwrittenbyMr.Swaroopisaverygoodguideforbothbrand-newprogrammersandnewpythonprogrammers.Took10halfdaystogothroughit.GreatHelp!--FangBiyi(PhDCandidateECE,MichiganStateUniversity)
Thankyoueversomuchforthisbook!!ThisbookclearedupmanyquestionsIhadaboutcertainaspectsofPythonsuchasobjectorientedprogramming.IdonotfeellikeanexpertatOObutIknowthisbookhelpedmeonafirststeportwo.Ihavenowwrittenseveralpythonprogramsthatactuallydorealthingsformeasasystemadministrator.Theyareallproceduralorientedbuttheyaresmallbymostpeoplesstandards.Again,thanksforthisbook.Thankyouforhavingitontheweb.--Bob
IjustwanttothankyouforwritingthefirstbookonprogrammingI'veeverreallyread.Pythonisnowmyfirstlanguage,andIcanjustimagineallthepossibilities.SothankyouforgivingmethetoolstocreatethingsIneverwouldhaveimaginedIcoulddobefore.--"TheWalrus"
IwantedtothankyouforwritingAByteOfPython(2&3Versions).IthasbeeninvaluabletomylearningexperienceinPython&Programmingingeneral.Needlesstosay,Iamabeginnerintheprogrammingworld,acoupleofmonthsofselfstudyuptothispoint.Ihadbeenusingyoutubetutorials&someotheronlinetutorialsincludingotherfreebooks.Idecidedtodigintoyourbookyesterday,&I'velearnedmoreonthefirstfewpagesthananyotherbookortutorial.AfewthingsIhadbeenconfusedabout,wereclearedrightupwithaGREATexample&explanation.Can'twaittoread(andlearn)more!!Thankyousomuchfornotonlywritingthebook,butforputtingitunderthecreativecommonslicense(free).Thankgoodnessthereareunselfishpeoplelikeyououttheretohelp&teachtherestofus.--Chris
Iwroteyoubackin2011andIwasjustgettingintoPythonandwantedtothankyouforyourtutorial"AByteofPython".Withoutit,Iwouldhavefallenbythewayside.SincethenIhavegoneontoprogramanumberoffunctionsinmyorganizationwiththislanguagewithyetmoreonthehorizon.IwouldnotcallmyselfanadvancedprogrammerbyanystretchbutInoticetheoccasionalrequestforassistancenowfromotherssinceIstartedusingit.Idiscovered,whilereading"Byte"whyIhadceasedstudyingCandC++anditwasbecausethebookgiventomestartedoutwithanexamplecontaininganaugmentedassignment.Ofcourse,therewasnoexplanationforthisarrangementofoperatorsandIfellonmyheadtryingtomakesenseofwhatwasonthewrittenpage.AsIrecallitwasamostfrustratingexercisewhichIeventuallyabandoned.Doesn'tmeanCorC++isimpossibletolearn,oreventhatIamstupid,butitdoesmeanthatthedocumentationIworkedmywaythroughdidnotdefinethesymbolsandwordswhichisanessentialpartofanyinstruction.Justascomputerswillnotbeabletounderstandacomputerwordorcomputersymbolthatisoutsidethesyntaxforthelanguagebeingused,astudentnewtoanyfieldwillnotgrasphissubjectifheencounterswordsorsymbolsforwhichtherearenodefinitions.Yougeta"bluescreen"asitwereineithercase.Thesolutionissimple,though:findthewordorsymbolandgettheproperdefinitionorsymbolandloandbehold,thecomputerorstudentcanproceed.Yourbook
Introduction
4
wassowellputtogetherthatIfoundverylittleinitIcouldn'tgrasp.So,thankyou.Iencourageyoutocontinuetoincludefulldefinitionsofterms.ThedocumentationwithPythonisgood,onceyouknow,(theexamplesareitsstrengthfromwhatIsee)butinmanycasesitseemsthatyouhavetoknowinordertounderstandthedocumentationwhichtomymindisnotwhatshouldbe.Thirdpartytutorialsexpresstheneedforclarificationofthedocumentationandtheirsuccesslargelydependsonthewordsthatareusedtodescribetheterminology.Ihaverecommendedyourbooktomanyothers.SomeinAustralia,someintheCaribbeanandyetothersintheUS.Itfillsanichenoothersdo.Ihopeyouaredoingwellandwishyouallthesuccessinthefuture.--Nick
hey,thisisankush(19).Iwasfacingagreatdifficultytostartwithpython.Itriedalotofbooksbutallwerebulkierandnottargetoriented;andthenifoundthislovelyone,whichmademelovepythoninnotime.Thanksalotforthis"beautifulpieceofbook".--Ankush
IwouldliketothankyouforyourexcellentguideonPython.Iamamolecularbiologist(withlittleprogrammingbackground)andformyworkIneedtohandlebigdatasetsofDNAsequencesandtoanalysemicroscopeimages.Forboththings,programminginpythonhasbeenuseful,ifnotessentialtocompleteandpublisha6-yearsproject.Thatsuchaguideisfreelyavailableisaclearsignthattheforcesofevilarenotyetrulingtheworld!:)--Luca
Sincethisisgoingtobethefirstlanguageyoulearn,youshoulduseAByteofPython.ItreallygivesaproperintroductionintoprogramminginPythonanditispacedwellenoughfortheaveragebeginner.Themostimportantthingfromthenonwillbeactuallystartingtopracticemakingyourownlittleprograms.--"{Unregistered}"
Justtosayaloudandhappythankyouverymuchforpublishing"AByteofPython"and"AByteofVim".ThosebookswereveryusefultomefourorfiveyearsagowhenIstartinglearningprogramming.RightnowI'mdevelopingaprojectthatwasadreamforalong,longtimeandjustwanttosaythankyou.Keepwalking.Youareasourceofmotivation.Allthebest.--Jocimar
FinishedreadingAbyteofPythonin3days.Itisthoroughlyinteresting.Notasinglepagewasboring.IwanttounderstandtheOrcascreenreadercode.Yourbookhashopefullyequippedmeforit.--Dattatray
Hi,'Abyteofpython'isreallyagoodreadingforpythonbeginners.So,again,NICEWORK!i'ma4yearsexperiencedJava&CdeveloperfromChina.Recently,iwanttodosomeworkonzim-wikinoteprojectwhichusespygtktoimplement.ireadyourbookin6days,andicanreadandwritepythoncodeexamplesnow.thxforyourcontribution.plzkeepyourenthusiasmtomakethisworldbetter,thisisjustalittleencouragefromChina.--Lee
IamIsenfromTaiwan,whoisagraduatingPhDstudentinElectricalEngineeringDepartmentofNationalTaiwanUniversity.Iwouldliketothankyouforyourgreatbook.IthinkitisnotonlyjusteasytoreadbutalsocomprehensiveandcompleteforanewcomerofPython.ThereasonIreadyourbookisthatIamstartingtoworkontheGNURadioframework.YourbookletmecatchmostofimportantcoreideasandskillofPythonwithaminimumtime.Ialsosawthatyoudonotmindthatreaderssendyouathanknoteinyourbook.SoIreallylikeyourbookandappreciateit.Thanks.--IsenI-ChunChao
ThebookisevenusedbyNASA!ItisusedintheirJetPropulsionLaboratorywiththeirDeepSpaceNetworkproject.
AcademicCourses
Thisbookis/wasbeingusedasinstructionalmaterialinvariouseducationalinstitutions:
'PrinciplesofProgrammingLanguages'courseatVrijeUniversiteit,Amsterdam'BasicConceptsofComputing'courseatUniversityofCalifornia,Davis'ProgrammingWithPython'courseatHarvardUniversity'IntroductiontoProgramming'courseatUniversityofLeeds'IntroductiontoApplicationProgramming'courseatBostonUniversity'InformationTechnologySkillsforMeteorology'courseatUniversityofOklahoma'Geoprocessing'courseatMichiganStateUniversity
Introduction
5
'MultiAgentSemanticWebSystems'courseattheUniversityofEdinburgh'IntroductiontoComputerScienceandProgramming'atMITOpenCourseWare'BasicprogrammingattheFacultyofSocialSciences,UniversityofLjubljana,Slovenia'--AlešŽibernasays"I(andmypredecessor)havebeenusingyourbookasthemainliteratureforthiscourse"'Introductiontoprogramming',DepartmentofInformationSciences,UniversityofZadar,Croatia--KrešimirZaudersays"IwouldliketoinformyouthatAByteofPythonisamandatoryreadatmycourse"
License
ThisbookislicensedunderaCreativeCommonsAttribution-ShareAlike4.0InternationalLicense.
Thismeans:
YouarefreetoSharei.e.tocopy,distributeandtransmitthisbookYouarefreetoRemixi.e.tomakechangestothisbook(especiallytranslations)Youarefreetouseitforcommercialpurposes
Pleasenote:
Pleasedonotsellelectronicorprintedcopiesofthebookunlessyouhaveclearlyandprominentlymentionedinthedescriptionthatthesecopiesarenotfromtheoriginalauthorofthisbook.Attributionmustbeshownintheintroductorydescriptionandfrontpageofthedocumentbylinkingbacktohttps://python.swaroopch.comandclearlyindicatingthattheoriginaltextcanbefetchedfromthislocation.Allthecode/scriptsprovidedinthisbookislicensedunderthe3-clauseBSDLicenseunlessotherwisenoted.
ReadNowYoucanreaditonlineathttps://python.swaroopch.com
BuyTheBookAprintedhardcopyofthebookcanbepurchasedathttps://swaroopch.com/buybookforyourofflinereadingpleasure,andtosupportthecontinueddevelopmentandimprovementofthisbook.
DownloadVisithttps://github.com/swaroopch/byte-of-python/releases/latesttodownloadaPDFfile(bestfordesktopreading)oranEPUBfile(bestfordevicessuchasmobile,tablet,ebookreaders).
Visithttps://github.com/swaroopch/byte-of-pythonfortherawcontent(forsuggestingcorrections,changes,translating,etc.)
Readthebookinyournativelanguage
Ifyouareinterestedinreadingorcontributingtranslationsofthisbooktootherhumanlanguages,pleaseseeTranslations.
Introduction
6
DedicationToKalyanVarmaandmanyotherseniorsatPESITwhointroducedustoGNU/Linuxandtheworldofopensource.
TothememoryofAtulChitnis,afriendandguidewhoshallbemissedgreatly.
TothepioneerswhomadetheInternethappen.Thisbookwasfirstwrittenin2003.Itstillremainspopular,thankstothenatureofsharingknowledgeontheInternetasenvisionedbythepioneers.
Dedication
7
PrefacePythonisprobablyoneofthefewprogramminglanguageswhichisbothsimpleandpowerful.Thisisgoodforbeginnersaswellasforexperts,andmoreimportantly,isfuntoprogramwith.Thisbookaimstohelpyoulearnthiswonderfullanguageandshowhowtogetthingsdonequicklyandpainlessly-ineffect'TheAnti-venomtoyourprogrammingproblems'.
WhoThisBookIsFor
ThisbookservesasaguideortutorialtothePythonprogramminglanguage.Itismainlytargetedatnewbies.Itisusefulforexperiencedprogrammersaswell.
Theaimisthatifallyouknowaboutcomputersishowtosavetextfiles,thenyoucanlearnPythonfromthisbook.Ifyouhavepreviousprogrammingexperience,thenyoucanalsolearnPythonfromthisbook.
Ifyoudohavepreviousprogrammingexperience,youwillbeinterestedinthedifferencesbetweenPythonandyourfavoriteprogramminglanguage-Ihavehighlightedmanysuchdifferences.Alittlewarningthough,Pythonissoongoingtobecomeyourfavoriteprogramminglanguage!
OfficialWebsiteTheofficialwebsiteofthebookishttps://python.swaroopch.comwhereyoucanreadthewholebookonline,downloadthelatestversionsofthebook,buyaprintedhardcopyandalsosendmefeedback.
SomethingToThinkAboutTherearetwowaysofconstructingasoftwaredesign:onewayistomakeitsosimplethatthereareobviouslynodeficiencies;theotheristomakeitsocomplicatedthattherearenoobviousdeficiencies.--C.A.R.Hoare
Successinlifeisamatternotsomuchoftalentandopportunityasofconcentrationandperseverance.--C.W.Wendte
Preface
8
AboutPythonPythonisoneofthoserarelanguageswhichcanclaimtobebothsimpleandpowerful.Youwillfindyourselfpleasantlysurprisedtoseehoweasyitistoconcentrateonthesolutiontotheproblemratherthanthesyntaxandstructureofthelanguageyouareprogrammingin.
TheofficialintroductiontoPythonis:
Pythonisaneasytolearn,powerfulprogramminglanguage.Ithasefficienthigh-leveldatastructuresandasimplebuteffectiveapproachtoobject-orientedprogramming.Python'selegantsyntaxanddynamictyping,togetherwithitsinterpretednature,makeitanideallanguageforscriptingandrapidapplicationdevelopmentinmanyareasonmostplatforms.
Iwilldiscussmostofthesefeaturesinmoredetailinthenextsection.
Storybehindthename
GuidovanRossum,thecreatorofthePythonlanguage,namedthelanguageaftertheBBCshow"MontyPython'sFlyingCircus".Hedoesn'tparticularlylikesnakesthatkillanimalsforfoodbywindingtheirlongbodiesaroundthemandcrushingthem.
FeaturesofPython
Simple
Pythonisasimpleandminimalisticlanguage.ReadingagoodPythonprogramfeelsalmostlikereadingEnglish,althoughverystrictEnglish!Thispseudo-codenatureofPythonisoneofitsgreateststrengths.Itallowsyoutoconcentrateonthesolutiontotheproblemratherthanthelanguageitself.
EasytoLearn
Asyouwillsee,Pythonisextremelyeasytogetstartedwith.Pythonhasanextraordinarilysimplesyntax,asalreadymentioned.
FreeandOpenSource
PythonisanexampleofaFLOSS(Free/LibreandOpenSourceSoftware).Insimpleterms,youcanfreelydistributecopiesofthissoftware,readitssourcecode,makechangestoit,andusepiecesofitinnewfreeprograms.FLOSSisbasedontheconceptofacommunitywhichsharesknowledge.ThisisoneofthereasonswhyPythonissogood-ithasbeencreatedandisconstantlyimprovedbyacommunitywhojustwanttoseeabetterPython.
High-levelLanguage
WhenyouwriteprogramsinPython,youneverneedtobotheraboutthelow-leveldetailssuchasmanagingthememoryusedbyyourprogram,etc.
Portable
Duetoitsopen-sourcenature,Pythonhasbeenportedto(i.e.changedtomakeitworkon)manyplatforms.AllyourPythonprogramscanworkonanyoftheseplatformswithoutrequiringanychangesatallifyouarecarefulenoughtoavoidanysystem-dependentfeatures.
AboutPython
9
YoucanusePythononGNU/Linux,Windows,FreeBSD,Macintosh,Solaris,OS/2,Amiga,AROS,AS/400,BeOS,OS/390,z/OS,PalmOS,QNX,VMS,Psion,AcornRISCOS,VxWorks,PlayStation,SharpZaurus,WindowsCEandPocketPC!
YoucanevenuseaplatformlikeKivytocreategamesforyourcomputerandforiPhone,iPad,andAndroid.
Interpreted
Thisrequiresabitofexplanation.
AprogramwritteninacompiledlanguagelikeCorC++isconvertedfromthesourcelanguagei.e.CorC++intoalanguagethatisspokenbyyourcomputer(binarycodei.e.0sand1s)usingacompilerwithvariousflagsandoptions.Whenyouruntheprogram,thelinker/loadersoftwarecopiestheprogramfromharddisktomemoryandstartsrunningit.
Python,ontheotherhand,doesnotneedcompilationtobinary.Youjustruntheprogramdirectlyfromthesourcecode.Internally,Pythonconvertsthesourcecodeintoanintermediateformcalledbytecodesandthentranslatesthisintothenativelanguageofyourcomputerandthenrunsit.Allthis,actually,makesusingPythonmucheasiersinceyoudon'thavetoworryaboutcompilingtheprogram,makingsurethattheproperlibrariesarelinkedandloaded,etc.ThisalsomakesyourPythonprogramsmuchmoreportable,sinceyoucanjustcopyyourPythonprogramontoanothercomputeranditjustworks!
ObjectOriented
Pythonsupportsprocedure-orientedprogrammingaswellasobject-orientedprogramming(OOP).Inprocedure-orientedlanguages,theprogramisbuiltaroundproceduresorfunctionswhicharenothingbutreusablepiecesofprograms.Inobject-orientedlanguages,theprogramisbuiltaroundobjectswhichcombinedataandfunctionality.PythonhasaverypowerfulbutsimplisticwayofdoingOOP,especiallywhencomparedtobiglanguageslikeC++orJava.
Extensible
Ifyouneedacriticalpieceofcodetorunveryfastorwanttohavesomepieceofalgorithmnottobeopen,youcancodethatpartofyourprograminCorC++andthenuseitfromyourPythonprogram.
Embeddable
YoucanembedPythonwithinyourC/C++programstogivescriptingcapabilitiesforyourprogram'susers.
ExtensiveLibraries
ThePythonStandardLibraryishugeindeed.Itcanhelpyoudovariousthingsinvolvingregularexpressions,documentationgeneration,unittesting,threading,databases,webbrowsers,CGI,FTP,email,XML,XML-RPC,HTML,WAVfiles,cryptography,GUI(graphicaluserinterfaces),andothersystem-dependentstuff.Remember,allthisisalwaysavailablewhereverPythonisinstalled.ThisiscalledtheBatteriesIncludedphilosophyofPython.
Besidesthestandardlibrary,therearevariousotherhigh-qualitylibrarieswhichyoucanfindatthePythonPackageIndex.
Summary
Pythonisindeedanexcitingandpowerfullanguage.IthastherightcombinationofperformanceandfeaturesthatmakewritingprogramsinPythonbothfunandeasy.
Python3versus2Youcanignorethissectionifyou'renotinterestedinthedifferencebetween"Pythonversion2"and"Pythonversion3".Butpleasedobeawareofwhichversionyouareusing.ThisbookiswrittenforPythonversion3.
AboutPython
10
Rememberthatonceyouhaveproperlyunderstoodandlearntouseoneversion,youcaneasilylearnthedifferencesandusetheotherone.ThehardpartislearningprogrammingandunderstandingthebasicsofPythonlanguageitself.Thatisourgoalinthisbook,andonceyouhaveachievedthatgoal,youcaneasilyusePython2orPython3dependingonyoursituation.
FordetailsondifferencesbetweenPython2andPython3,see:
ThefutureofPython2PortingPython2CodetoPython3WritingcodethatrunsunderbothPython2and3SupportingPython3:Anin-depthguide
WhatProgrammersSayYoumayfinditinterestingtoreadwhatgreathackerslikeEricS.Raymond(ESR)havetosayaboutPython:
EricS.Raymondistheauthorof"TheCathedralandtheBazaar"andisalsothepersonwhocoinedthetermOpenSource.HesaysthatPythonhasbecomehisfavoriteprogramminglanguage.ThisarticlewastherealinspirationformyfirstbrushwithPython.BruceEckelistheauthorofthefamous'ThinkinginJava'and'ThinkinginC++'books.HesaysthatnolanguagehasmadehimmoreproductivethanPython.HesaysthatPythonisperhapstheonlylanguagethatfocusesonmakingthingseasierfortheprogrammer.Readthecompleteinterviewformoredetails.PeterNorvigisawell-knownLispauthorandDirectorofSearchQualityatGoogle(thankstoGuidovanRossumforpointingthatout).HesaysthatwritingPythonislikewritinginpseudocode.HesaysthatPythonhasalwaysbeenanintegralpartofGoogle.YoucanactuallyverifythisstatementbylookingattheGoogleJobspagewhichlistsPythonknowledgeasarequirementforsoftwareengineers.
AboutPython
11
InstallationWhenwereferto"Python3"inthisbook,wewillbereferringtoanyversionofPythonequaltoorgreaterthanversionPython3.6.0.
InstallationonWindows
Visithttps://www.python.org/downloads/anddownloadthelatestversion.Atthetimeofthiswriting,itwasPython3.5.1TheinstallationisjustlikeanyotherWindows-basedsoftware.
NotethatifyourWindowsversionispre-Vista,youshoulddownloadPython3.4onlyaslaterversionsrequirenewerversionsofWindows.
CAUTION:Makesureyoucheckoption AddPython3.5toPATH.
Tochangeinstalllocation,clickon Customizeinstallation,then Nextandenter C:\python35(oranotherappropriatelocation)astheinstalllocation.
Ifyoudidn�tcheckthe AddPython3.5PATHoptionearlier,check AddPythontoenvironmentvariables.Thisdoesthesamethingas AddPython3.5toPATHonthefirstinstallscreen.
YoucanchoosetoinstallLauncherforallusersornot,itdoesnotmattermuch.LauncherisusedtoswitchbetweendifferentversionsofPythoninstalled.
Ifyourpathwasnotsetcorrectly(bycheckingthe AddPython3.5Pathor AddPythontoenvironmentvariablesoptions),thenfollowthestepsinthenextsection( DOSPrompt)tofixit.Otherwise,gotothe RunningPythonpromptonWindowssectioninthisdocument.
NOTE:Forpeoplewhoalreadyknowprogramming,ifyouarefamiliarwithDocker,checkoutPythoninDockerandDockeronWindows.
DOSPrompt
IfyouwanttobeabletousePythonfromtheWindowscommandlinei.e.theDOSprompt,thenyouneedtosetthePATHvariableappropriately.
ForWindows2000,XP,2003,clickon ControlPanel-> System-> Advanced-> EnvironmentVariables.Clickonthevariablenamed PATHintheSystemVariablessection,thenselect Editandadd ;C:\Python35(pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Ofcourse,usetheappropriatedirectoryname.
ForolderversionsofWindows,openthefile C:\AUTOEXEC.BATandaddtheline PATH=%PATH%;C:\Python35andrestartthesystem.ForWindowsNT,usethe AUTOEXEC.NTfile.
ForWindowsVista:
ClickStartandchoose ControlPanelClickSystem,ontherightyou'llsee"Viewbasicinformationaboutyourcomputer"Ontheleftisalistoftasks,thelastofwhichis Advancedsystemsettings.Clickthat.The Advancedtabofthe SystemPropertiesdialogboxisshown.Clickthe EnvironmentVariablesbuttononthebottomright.Inthelowerboxtitled SystemVariablesscrolldowntoPathandclickthe Editbutton.Changeyourpathasneedbe.Restartyoursystem.Vistadidn'tpickupthesystempathenvironmentvariablechangeuntilIrestarted.
Installation
12
ForWindows7and8:
RightclickonComputerfromyourdesktopandselect Propertiesorclick Startandchoose ControlPanel->SystemandSecurity-> System.Clickon Advancedsystemsettingsontheleftandthenclickonthe Advancedtab.Atthebottomclickon EnvironmentVariablesandunder Systemvariables,lookforthe PATHvariable,selectandthenpress Edit.GototheendofthelineunderVariablevalueandappend ;C:\Python35(pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Ofcourse,usetheappropriatefoldername.Ifthevaluewas %SystemRoot%\system32;Itwillnowbecome %SystemRoot%\system32;C:\Python36Click OKandyouaredone.Norestartisrequired,howeveryoumayhavetocloseandreopenthecommandline.
ForWindows10:
WindowsStartMenu> Settings> About> SystemInfo(thisisallthewayovertotheright)> AdvancedSystemSettings> EnvironmentVariables(thisistowardsthebottom)>(thenhighlight Pathvariableandclick Edit)> New>(typeinwhateveryourpythonlocationis.Forexample, C:\Python35\)
RunningPythonpromptonWindows
ForWindowsusers,youcanruntheinterpreterinthecommandlineifyouhavesetthe PATHvariableappropriately.
ToopentheterminalinWindows,clickthestartbuttonandclick Run.Inthedialogbox,type cmdandpress [enter]key.
Then,type pythonandensuretherearenoerrors.
InstallationonMacOSX
ForMacOSXusers,useHomebrew: brewinstallpython3.
Toverify,opentheterminalbypressing [Command+Space]keys(toopenSpotlightsearch),type Terminalandpress[enter]key.Now,run python3andensuretherearenoerrors.
InstallationonGNU/Linux
ForGNU/Linuxusers,useyourdistribution'spackagemanagertoinstallPython3,e.g.onDebian&Ubuntu: sudoapt-getupdate&&sudoapt-getinstallpython3.
Toverify,opentheterminalbyopeningthe Terminalapplicationorbypressing Alt+F2andentering gnome-terminal.Ifthatdoesn'twork,pleasereferthedocumentationofyourparticularGNU/Linuxdistribution.Now,run python3andensuretherearenoerrors.
YoucanseetheversionofPythononthescreenbyrunning:
$python3-V
Python3.6.0
NOTE: $isthepromptoftheshell.Itwillbedifferentforyoudependingonthesettingsoftheoperatingsystemonyourcomputer,henceIwillindicatethepromptbyjustthe $symbol.
CAUTION:Outputmaybedifferentonyourcomputer,dependingontheversionofPythonsoftwareinstalledonyourcomputer.
Summary
Installation
13
Fromnowon,wewillassumethatyouhavePythoninstalledonyoursystem.
Next,wewillwriteourfirstPythonprogram.
Installation
14
FirstStepsWewillnowseehowtorunatraditional'HelloWorld'programinPython.Thiswillteachyouhowtowrite,saveandrunPythonprograms.
TherearetwowaysofusingPythontorunyourprogram-usingtheinteractiveinterpreterpromptorusingasourcefile.Wewillnowseehowtousebothofthesemethods.
UsingTheInterpreterPrompt
Opentheterminalinyouroperatingsystem(asdiscussedpreviouslyintheInstallationchapter)andthenopenthePythonpromptbytyping python3andpressing [enter]key.
OnceyouhavestartedPython,youshouldsee >>>whereyoucanstarttypingstuff.ThisiscalledthePythoninterpreterprompt.
AtthePythoninterpreterprompt,type:
print("HelloWorld")
followedbythe [enter]key.Youshouldseethewords HelloWorldprintedtothescreen.
Hereisanexampleofwhatyoushouldbeseeing,whenusingaMacOSXcomputer.ThedetailsaboutthePythonsoftwarewilldifferbasedonyourcomputer,butthepartfromtheprompt(i.e.from >>>onwards)shouldbethesameregardlessoftheoperatingsystem.
$python3
Python3.6.0(default,Jan122017,11:26:36)
[GCC4.2.1CompatibleAppleLLVM8.0.0(clang-800.0.38)]ondarwin
Type"help","copyright","credits"or"license"formoreinformation.
>>>print("HelloWorld")
HelloWorld
NoticethatPythongivesyoutheoutputofthelineimmediately!WhatyoujustenteredisasinglePythonstatement.Weuseprintto(unsurprisingly)printanyvaluethatyousupplytoit.Here,wearesupplyingthetext HelloWorldandthisispromptlyprintedtothescreen.
HowtoQuittheInterpreterPrompt
IfyouareusingaGNU/LinuxorOSXshell,youcanexittheinterpreterpromptbypressing [ctrl+d]orentering exit()(note:remembertoincludetheparentheses, ())followedbythe [enter]key.
IfyouareusingtheWindowscommandprompt,press [ctrl+z]followedbythe [enter]key.
ChoosingAnEditor
Wecannottypeoutourprogramattheinterpreterprompteverytimewewanttorunsomething,sowehavetosavetheminfilesandcanrunourprogramsanynumberoftimes.
TocreateourPythonsourcefiles,weneedaneditorsoftwarewhereyoucantypeandsave.Agoodprogrammer'seditorwillmakeyourlifeeasierinwritingthesourcefiles.Hence,thechoiceofaneditoriscrucialindeed.Youhavetochooseaneditorasyouwouldchooseacaryouwouldbuy.AgoodeditorwillhelpyouwritePythonprogramseasily,makingyourjourneymorecomfortableandhelpsyoureachyourdestination(achieveyourgoal)inamuchfasterandsaferway.
FirstSteps
15
OneoftheverybasicrequirementsissyntaxhighlightingwhereallthedifferentpartsofyourPythonprogramarecolorizedsothatyoucanseeyourprogramandvisualizeitsrunning.
Ifyouhavenoideawheretostart,IwouldrecommendusingPyCharmEducationalEditionsoftwarewhichisavailableonWindows,MacOSXandGNU/Linux.Detailsinthenextsection.
IfyouareusingWindows,donotuseNotepad-itisabadchoicebecauseitdoesnotdosyntaxhighlightingandalsoimportantlyitdoesnotsupportindentationofthetextwhichisveryimportantinourcaseaswewillseelater.Goodeditorswillautomaticallydothis.
Ifyouareanexperiencedprogrammer,thenyoumustbealreadyusingVimorEmacs.Needlesstosay,thesearetwoofthemostpowerfuleditorsandyouwillbenefitfromusingthemtowriteyourPythonprograms.Ipersonallyusebothformostofmyprograms,andhaveevenwrittenanentirebookonVim.
IncaseyouarewillingtotakethetimetolearnVimorEmacs,thenIhighlyrecommendthatyoudolearntouseeitherofthemasitwillbeveryusefulforyouinthelongrun.However,asImentionedbefore,beginnerscanstartwithPyCharmandfocusthelearningonPythonratherthantheeditoratthismoment.
Toreiterate,pleasechooseapropereditor-itcanmakewritingPythonprogramsmorefunandeasy.
PyCharm
PyCharmEducationalEditionisafreeeditorwhichyoucanuseforwritingPythonprograms.
WhenyouopenPyCharm,you'llseethis,clickon CreateNewProject:
FirstSteps
16
Change untitledto helloworldasthelocationoftheproject,youshouldseedetailssimilartothis:
FirstSteps
18
Clickthe Createbutton.
Right-clickonthe helloworldinthesidebarandselect New-> PythonFile:
FirstSteps
19
Deletethelinesthatarealreadypresent,andnowtypethefollowing:
print("helloworld")
Nowright-clickonwhatyoutyped(withoutselectingthetext),andclickon Run'hello'.
Youshouldnowseetheoutput(whatitprints)ofyourprogram:
FirstSteps
21
Phew!Thatwasquiteafewstepstogetstarted,buthenceforth,everytimeweaskyoutocreateanewfile,remembertojustright-clickon helloworldontheleft-> New-> PythonFileandcontinuethesamestepstotypeandrunasshownabove.
YoucanfindmoreinformationaboutPyCharminthePyCharmQuickstartpage.
Vim1. InstallVim
MacOSXusersshouldinstall macvimpackageviaHomeBrewWindowsusersshoulddownloadthe"self-installingexecutable"fromVimwebsiteGNU/LinuxusersshouldgetVimfromtheirdistribution'ssoftwarerepositories,e.g.DebianandUbuntuuserscaninstallthe vimpackage.
2. Installjedi-vimpluginforautocompletion.3. Installcorresponding jedipythonpackage: pipinstall-Ujedi
Emacs1. InstallEmacs24+.
MacOSXusersshouldgetEmacsfromhttp://emacsformacosx.comWindowsusersshouldgetEmacsfromhttp://ftp.gnu.org/gnu/emacs/windows/GNU/LinuxusersshouldgetEmacsfromtheirdistribution'ssoftwarerepositories,e.g.DebianandUbuntuuserscaninstallthe emacs24package.
2. InstallELPY
UsingASourceFile
FirstSteps
22
Nowlet'sgetbacktoprogramming.Thereisatraditionthatwheneveryoulearnanewprogramminglanguage,thefirstprogramthatyouwriteandrunisthe'HelloWorld'program-allitdoesisjustsay'HelloWorld'whenyourunit.AsSimonCozens says,itisthe"traditionalincantationtotheprogramminggodstohelpyoulearnthelanguagebetter."
Startyourchoiceofeditor,enterthefollowingprogramandsaveitas hello.py.
IfyouareusingPyCharm,wehavealreadydiscussedhowtorunfromasourcefile.
Forothereditors,openanewfile hello.pyandtypethis:
print("helloworld")
Whereshouldyousavethefile?Toanyfolderforwhichyouknowthelocationofthefolder.Ifyoudon'tunderstandwhatthatmeans,createanewfolderandusethatlocationtosaveandrunallyourPythonprograms:
/tmp/pyonMacOSX/tmp/pyonGNU/LinuxC:\pyonWindows
Tocreatetheabovefolder(fortheoperatingsystemyouareusing),usethe mkdircommandintheterminal,forexample, mkdir/tmp/py.
IMPORTANT:Alwaysensurethatyougiveitthefileextensionof .py,forexample, foo.py.
TorunyourPythonprogram:
1. Openaterminalwindow(seethepreviousInstallationchapteronhowtodothat)2. Changedirectorytowhereyousavedthefile,forexample, cd/tmp/py3. Runtheprogrambyenteringthecommand pythonhello.py.Theoutputisasshownbelow.
$pythonhello.py
helloworld
1
FirstSteps
23
Ifyougottheoutputasshownabove,congratulations!-youhavesuccessfullyrunyourfirstPythonprogram.Youhavesuccessfullycrossedthehardestpartoflearningprogramming,whichis,gettingstartedwithyourfirstprogram!
Incaseyougotanerror,pleasetypetheaboveprogramexactlyasshownaboveandruntheprogramagain.NotethatPythoniscase-sensitivei.e. printisnotthesameas Print-notethelowercase pintheformerandtheuppercase Pinthelatter.Also,ensuretherearenospacesortabsbeforethefirstcharacterineachline-wewillseewhythisisimportantlater.
HowItWorks
APythonprogramiscomposedofstatements.Inourfirstprogram,wehaveonlyonestatement.Inthisstatement,wecalltheprintstatementtowhichwesupplythetext"helloworld".
GettingHelp
IfyouneedquickinformationaboutanyfunctionorstatementinPython,thenyoucanusethebuilt-in helpfunctionality.Thisisveryusefulespeciallywhenusingtheinterpreterprompt.Forexample,run help('len')-thisdisplaysthehelpforthe lenfunctionwhichisusedtocountnumberofitems.
TIP:Press qtoexitthehelp.
Similarly,youcanobtaininformationaboutalmostanythinginPython.Use help()tolearnmoreaboutusing helpitself!
Incaseyouneedtogethelpforoperatorslike return,thenyouneedtoputthoseinsidequotessuchas help('return')sothatPythondoesn'tgetconfusedonwhatwe'retryingtodo.
Summary
Youshouldnowbeabletowrite,saveandrunPythonprogramsatease.
NowthatyouareaPythonuser,let'slearnsomemorePythonconcepts.
.theauthoroftheamazing'BeginningPerl'book↩1
FirstSteps
24
BasicsJustprinting helloworldisnotenough,isit?Youwanttodomorethanthat-youwanttotakesomeinput,manipulateitandgetsomethingoutofit.WecanachievethisinPythonusingconstantsandvariables,andwe'lllearnsomeotherconceptsaswellinthischapter.
Comments
Commentsareanytexttotherightofthe #symbolandismainlyusefulasnotesforthereaderoftheprogram.
Forexample:
print('helloworld')#Notethatprintisafunction
or:
#Notethatprintisafunction
print('helloworld')
Useasmanyusefulcommentsasyoucaninyourprogramto:
explainassumptionsexplainimportantdecisionsexplainimportantdetailsexplainproblemsyou'retryingtosolveexplainproblemsyou'retryingtoovercomeinyourprogram,etc.
Codetellsyouhow,commentsshouldtellyouwhy.
Thisisusefulforreadersofyourprogramsothattheycaneasilyunderstandwhattheprogramisdoing.Remember,thatpersoncanbeyourselfaftersixmonths!
LiteralConstants
Anexampleofaliteralconstantisanumberlike 5, 1.23,orastringlike 'Thisisastring'or "It'sastring!".
Itiscalledaliteralbecauseitisliteral-youuseitsvalueliterally.Thenumber 2alwaysrepresentsitselfandnothingelse-itisaconstantbecauseitsvaluecannotbechanged.Hence,allthesearereferredtoasliteralconstants.
Numbers
Numbersaremainlyoftwotypes-integersandfloats.
Anexampleofanintegeris 2whichisjustawholenumber.
Examplesoffloatingpointnumbers(orfloatsforshort)are 3.23and 52.3E-4.The Enotationindicatespowersof10.Inthiscase, 52.3E-4means 52.3*10^-4^.
NoteforExperiencedProgrammers
Thereisnoseparate longtype.The inttypecanbeanintegerofanysize.
Basics
25
Strings
Astringisasequenceofcharacters.Stringsarebasicallyjustabunchofwords.
YouwillbeusingstringsinalmosteveryPythonprogramthatyouwrite,sopayattentiontothefollowingpart.
SingleQuote
Youcanspecifystringsusingsinglequotessuchas 'Quotemeonthis'.
Allwhitespacei.e.spacesandtabs,withinthequotes,arepreservedas-is.
DoubleQuotes
Stringsindoublequotesworkexactlythesamewayasstringsinsinglequotes.Anexampleis "What'syourname?".
TripleQuotes
Youcanspecifymulti-linestringsusingtriplequotes-( """or ''').Youcanusesinglequotesanddoublequotesfreelywithinthetriplequotes.Anexampleis:
'''Thisisamulti-linestring.Thisisthefirstline.
Thisisthesecondline.
"What'syourname?,"Iasked.
Hesaid"Bond,JamesBond."
'''
StringsAreImmutable
Thismeansthatonceyouhavecreatedastring,youcannotchangeit.Althoughthismightseemlikeabadthing,itreallyisn't.Wewillseewhythisisnotalimitationinthevariousprogramsthatweseelateron.
NoteforC/C++Programmers
Thereisnoseparate chardatatypeinPython.ThereisnorealneedforitandIamsureyouwon'tmissit.
NoteforPerl/PHPProgrammers
Rememberthatsingle-quotedstringsanddouble-quotedstringsarethesame-theydonotdifferinanyway.
Theformatmethod
Sometimeswemaywanttoconstructstringsfromotherinformation.Thisiswherethe format()methodisuseful.
Savethefollowinglinesasafile str_format.py:
age=20
name='Swaroop'
print('{0}was{1}yearsoldwhenhewrotethisbook'.format(name,age))
print('Whyis{0}playingwiththatpython?'.format(name))
Output:
$pythonstr_format.py
Swaroopwas20yearsoldwhenhewrotethisbook
WhyisSwaroopplayingwiththatpython?
Basics
26
HowItWorks
Astringcanusecertainspecificationsandsubsequently,the formatmethodcanbecalledtosubstitutethosespecificationswithcorrespondingargumentstothe formatmethod.
Observethefirstusagewhereweuse {0}andthiscorrespondstothevariable namewhichisthefirstargumenttotheformatmethod.Similarly,thesecondspecificationis {1}correspondingto agewhichisthesecondargumenttotheformatmethod.NotethatPythonstartscountingfrom0whichmeansthatfirstpositionisatindex0,secondpositionisatindex1,andsoon.
Noticethatwecouldhaveachievedthesameusingstringconcatenation:
name+'is'+str(age)+'yearsold'
butthatismuchuglierandmoreerror-prone.Second,theconversiontostringwouldbedoneautomaticallybythe formatmethodinsteadoftheexplicitconversiontostringsneededinthiscase.Third,whenusingthe formatmethod,wecanchangethemessagewithouthavingtodealwiththevariablesusedandvice-versa.
Alsonotethatthenumbersareoptional,soyoucouldhavealsowrittenas:
age=20
name='Swaroop'
print('{}was{}yearsoldwhenhewrotethisbook'.format(name,age))
print('Whyis{}playingwiththatpython?'.format(name))
whichwillgivethesameexactoutputasthepreviousprogram.
Wecanalsonametheparameters:
age=20
name='Swaroop'
print('{name}was{age}yearsoldwhenhewrotethisbook'.format(name=name,age=age))
print('Whyis{name}playingwiththatpython?'.format(name=name))
whichwillgivethesameexactoutputasthepreviousprogram.
Python3.6introducedashorterwaytodonamedparameters,called"f-strings":
age=20
name='Swaroop'
print(f'{name}was{age}yearsoldwhenhewrotethisbook')#noticethe'f'beforethestring
print(f'Whyis{name}playingwiththatpython?')#noticethe'f'beforethestring
whichwillgivethesameexactoutputasthepreviousprogram.
WhatPythondoesinthe formatmethodisthatitsubstituteseachargumentvalueintotheplaceofthespecification.Therecanbemoredetailedspecificationssuchas:
#decimal(.)precisionof3forfloat'0.333'
print('{0:.3f}'.format(1.0/3))
#fillwithunderscores(_)withthetextcentered
#(^)to11width'___hello___'
print('{0:_^11}'.format('hello'))
#keyword-based'SwaroopwroteAByteofPython'
print('{name}wrote{book}'.format(name='Swaroop',book='AByteofPython'))
Basics
27
Output:
0.333
___hello___
SwaroopwroteAByteofPython
Sincewearediscussingformatting,notethat printalwaysendswithaninvisible"newline"character( \n)sothatrepeatedcallsto printwillallprintonaseparatelineeach.Topreventthisnewlinecharacterfrombeingprinted,youcanspecifythatitshould endwithablank:
print('a',end='')
print('b',end='')
Outputis:
ab
Oryoucan endwithaspace:
print('a',end='')
print('b',end='')
print('c')
Outputis:
abc
EscapeSequences
Suppose,youwanttohaveastringwhichcontainsasinglequote( '),howwillyouspecifythisstring?Forexample,thestringis "What'syourname?".Youcannotspecify 'What'syourname?'becausePythonwillbeconfusedastowherethestringstartsandends.So,youwillhavetospecifythatthissinglequotedoesnotindicatetheendofthestring.Thiscanbedonewiththehelpofwhatiscalledanescapesequence.Youspecifythesinglequoteas \':noticethebackslash.Now,youcanspecifythestringas 'What\'syourname?'.
Anotherwayofspecifyingthisspecificstringwouldbe "What'syourname?"i.e.usingdoublequotes.Similarly,youhavetouseanescapesequenceforusingadoublequoteitselfinadoublequotedstring.Also,youhavetoindicatethebackslashitselfusingtheescapesequence \\.
Whatifyouwantedtospecifyatwo-linestring?Onewayistouseatriple-quotedstringasshownpreviouslyoryoucanuseanescapesequenceforthenewlinecharacter- \ntoindicatethestartofanewline.Anexampleis:
'Thisisthefirstline\nThisisthesecondline'
Anotherusefulescapesequencetoknowisthetab: \t.TherearemanymoreescapesequencesbutIhavementionedonlythemostusefuloneshere.
Onethingtonoteisthatinastring,asinglebackslashattheendofthelineindicatesthatthestringiscontinuedinthenextline,butnonewlineisadded.Forexample:
"Thisisthefirstsentence.\
Thisisthesecondsentence."
Basics
28
isequivalentto
"Thisisthefirstsentence.Thisisthesecondsentence."
RawString
Ifyouneedtospecifysomestringswherenospecialprocessingsuchasescapesequencesarehandled,thenwhatyouneedistospecifyarawstringbyprefixing ror Rtothestring.Anexampleis:
r"Newlinesareindicatedby\n"
NoteforRegularExpressionUsers
Alwaysuserawstringswhendealingwithregularexpressions.Otherwise,alotofbackwhackingmayberequired.Forexample,backreferencescanbereferredtoas '\\1'or r'\1'.
Variable
Usingjustliteralconstantscansoonbecomeboring-weneedsomewayofstoringanyinformationandmanipulatethemaswell.Thisiswherevariablescomeintothepicture.Variablesareexactlywhatthenameimplies-theirvaluecanvary,i.e.,youcanstoreanythingusingavariable.Variablesarejustpartsofyourcomputer'smemorywhereyoustoresomeinformation.Unlikeliteralconstants,youneedsomemethodofaccessingthesevariablesandhenceyougivethemnames.
IdentifierNaming
Variablesareexamplesofidentifiers.Identifiersarenamesgiventoidentifysomething.Therearesomerulesyouhavetofollowfornamingidentifiers:
Thefirstcharacteroftheidentifiermustbealetterofthealphabet(uppercaseASCIIorlowercaseASCIIorUnicodecharacter)oranunderscore( _).Therestoftheidentifiernamecanconsistofletters(uppercaseASCIIorlowercaseASCIIorUnicodecharacter),underscores( _)ordigits(0-9).Identifiernamesarecase-sensitive.Forexample, mynameand myNamearenotthesame.Notethelowercase nintheformerandtheuppercase Ninthelatter.Examplesofvalididentifiernamesare i, name_2_3.Examplesofinvalididentifiernamesare 2things, thisisspacedout, my-nameand >a1b2_c3.
DataTypesVariablescanholdvaluesofdifferenttypescalleddatatypes.Thebasictypesarenumbersandstrings,whichwehavealreadydiscussed.Inlaterchapters,wewillseehowtocreateourowntypesusingclasses.
ObjectRemember,Pythonreferstoanythingusedinaprogramasanobject.Thisismeantinthegenericsense.Insteadofsaying"thesomething"',wesay"theobject".
NoteforObjectOrientedProgrammingusers:
Pythonisstronglyobject-orientedinthesensethateverythingisanobjectincludingnumbers,stringsandfunctions.
Basics
29
Wewillnowseehowtousevariablesalongwithliteralconstants.Savethefollowingexampleandruntheprogram.
HowtowritePythonprograms
Henceforth,thestandardproceduretosaveandrunaPythonprogramisasfollows:
ForPyCharm
1. OpenPyCharm.2. Createnewfilewiththefilenamementioned.3. Typetheprogramcodegivenintheexample.4. Right-clickandrunthecurrentfile.
NOTE:Wheneveryouhavetoprovidecommandlinearguments,clickon Run-> EditConfigurationsandtypetheargumentsinthe Scriptparameters:sectionandclickthe OKbutton:
Forothereditors
1. Openyoureditorofchoice.2. Typetheprogramcodegivenintheexample.3. Saveitasafilewiththefilenamementioned.4. Runtheinterpreterwiththecommand pythonprogram.pytoruntheprogram.
Example:UsingVariablesAndLiteralConstants
Typeandrunthefollowingprogram:
#Filename:var.py
i=5
print(i)
i=i+1
Basics
30
print(i)
s='''Thisisamulti-linestring.
Thisisthesecondline.'''
print(s)
Output:
5
6
Thisisamulti-linestring.
Thisisthesecondline.
HowItWorks
Here'showthisprogramworks.First,weassigntheliteralconstantvalue 5tothevariable iusingtheassignmentoperator( =).Thislineiscalledastatementbecauseitstatesthatsomethingshouldbedoneandinthiscase,weconnectthevariablenameitothevalue 5.Next,weprintthevalueof iusingthe printstatementwhich,unsurprisingly,justprintsthevalueofthevariabletothescreen.
Thenweadd 1tothevaluestoredin iandstoreitback.Wethenprintitandexpectedly,wegetthevalue 6.
Similarly,weassigntheliteralstringtothevariable sandthenprintit.
Noteforstaticlanguageprogrammers
Variablesareusedbyjustassigningthemavalue.Nodeclarationordatatypedefinitionisneeded/used.
LogicalAndPhysicalLine
Aphysicallineiswhatyouseewhenyouwritetheprogram.AlogicallineiswhatPythonseesasasinglestatement.Pythonimplicitlyassumesthateachphysicallinecorrespondstoalogicalline.
Anexampleofalogicallineisastatementlike print('helloworld')-ifthiswasonalinebyitself(asyouseeitinaneditor),thenthisalsocorrespondstoaphysicalline.
Implicitly,Pythonencouragestheuseofasinglestatementperlinewhichmakescodemorereadable.
Ifyouwanttospecifymorethanonelogicallineonasinglephysicalline,thenyouhavetoexplicitlyspecifythisusingasemicolon( ;)whichindicatestheendofalogicalline/statement.Forexample:
i=5
print(i)
iseffectivelysameas
i=5;
print(i);
whichisalsosameas
i=5;print(i);
andsameas
i=5;print(i)
Basics
31
However,Istronglyrecommendthatyousticktowritingamaximumofasinglelogicallineoneachsinglephysicalline.Theideaisthatyoushouldneverusethesemicolon.Infact,IhaveneverusedorevenseenasemicoloninaPythonprogram.
Thereisonekindofsituationwherethisconceptisreallyuseful:ifyouhavealonglineofcode,youcanbreakitintomultiplephysicallinesbyusingthebackslash.Thisisreferredtoasexplicitlinejoining:
s='Thisisastring.\
Thiscontinuesthestring.'
print(s)
Output:
Thisisastring.Thiscontinuesthestring.
Similarly,
i=\
5
isthesameas
i=5
Sometimes,thereisanimplicitassumptionwhereyoudon'tneedtouseabackslash.Thisisthecasewherethelogicallinehasastartingparentheses,startingsquarebracketsorastartingcurlybracesbutnotanendingone.Thisiscalledimplicitlinejoining.Youcanseethisinactionwhenwewriteprogramsusinglistinlaterchapters.
Indentation
WhitespaceisimportantinPython.Actually,whitespaceatthebeginningofthelineisimportant.Thisiscalledindentation.Leadingwhitespace(spacesandtabs)atthebeginningofthelogicallineisusedtodeterminetheindentationlevelofthelogicalline,whichinturnisusedtodeterminethegroupingofstatements.
Thismeansthatstatementswhichgotogethermusthavethesameindentation.Eachsuchsetofstatementsiscalledablock.Wewillseeexamplesofhowblocksareimportantinlaterchapters.
Onethingyoushouldrememberisthatwrongindentationcangiverisetoerrors.Forexample:
i=5
#Errorbelow!Noticeasinglespaceatthestartoftheline
print('Valueis',i)
print('Irepeat,thevalueis',i)
Whenyourunthis,yougetthefollowingerror:
File"whitespace.py",line3
print('Valueis',i)
^
IndentationError:unexpectedindent
Noticethatthereisasinglespaceatthebeginningofthesecondline.TheerrorindicatedbyPythontellsusthatthesyntaxoftheprogramisinvalidi.e.theprogramwasnotproperlywritten.Whatthismeanstoyouisthatyoucannotarbitrarilystartnewblocksofstatements(exceptforthedefaultmainblockwhichyouhavebeenusingallalong,ofcourse).Caseswhereyoucanuse
Basics
32
newblockswillbedetailedinlaterchapterssuchasthecontrolflow.
Howtoindent
Usefourspacesforindentation.ThisistheofficialPythonlanguagerecommendation.Goodeditorswillautomaticallydothisforyou.Makesureyouuseaconsistentnumberofspacesforindentation,otherwiseyourprogramwillnotrunorwillhaveunexpectedbehavior.
Notetostaticlanguageprogrammers
Pythonwillalwaysuseindentationforblocksandwillneverusebraces.Run from__future__importbracestolearnmore.
SummaryNowthatwehavegonethroughmanynitty-grittydetails,wecanmoveontomoreinterestingstuffsuchascontrolflowstatements.Besuretobecomecomfortablewithwhatyouhavereadinthischapter.
Basics
33
OperatorsandExpressionsMoststatements(logicallines)thatyouwritewillcontainexpressions.Asimpleexampleofanexpressionis 2+3.Anexpressioncanbebrokendownintooperatorsandoperands.
Operatorsarefunctionalitythatdosomethingandcanberepresentedbysymbolssuchas +orbyspecialkeywords.Operatorsrequiresomedatatooperateonandsuchdataiscalledoperands.Inthiscase, 2and 3aretheoperands.
Operators
Wewillbrieflytakealookattheoperatorsandtheirusage.
Notethatyoucanevaluatetheexpressionsgivenintheexamplesusingtheinterpreterinteractively.Forexample,totesttheexpression 2+3,usetheinteractivePythoninterpreterprompt:
>>>2+3
5
>>>3*5
15
>>>
Hereisaquickoverviewoftheavailableoperators:
+(plus)
Addstwoobjects3+5gives 8. 'a'+'b'gives 'ab'.
-(minus)
Givesthesubtractionofonenumberfromtheother;ifthefirstoperandisabsentitisassumedtobezero.-5.2givesanegativenumberand 50-24gives 26.
*(multiply)
Givesthemultiplicationofthetwonumbersorreturnsthestringrepeatedthatmanytimes.2*3gives 6. 'la'*3gives 'lalala'.
**(power)
Returnsxtothepowerofy3**4gives 81(i.e. 3*3*3*3)
/(divide)
Dividexbyy13/3gives 4.333333333333333
//(divideandfloor)
Dividexbyyandroundtheanswerdowntothenearestintegervalue.Notethatifoneofthevaluesisafloat,you'llgetbackafloat.13//3gives 4-13//3gives -59//1.81gives 4.0
%(modulo)
Returnstheremainderofthedivision13%3gives 1. -25.5%2.25gives 1.5.
OperatorsandExpressions
34
<<(leftshift)
Shiftsthebitsofthenumbertotheleftbythenumberofbitsspecified.(Eachnumberisrepresentedinmemorybybitsorbinarydigitsi.e.0and1)2<<2gives 8. 2isrepresentedby 10inbits.Leftshiftingby2bitsgives 1000whichrepresentsthedecimal 8.
>>(rightshift)
Shiftsthebitsofthenumbertotherightbythenumberofbitsspecified.11>>1gives 5.11isrepresentedinbitsby 1011whichwhenrightshiftedby1bitgives 101whichisthedecimal 5.
&(bit-wiseAND)
Bit-wiseANDofthenumbers:ifbothbitsare 1,theresultis 1.Otherwise,it's 0.5&3gives 1( 0101&0011gives 0001)
|(bit-wiseOR)
BitwiseORofthenumbers:ifbothbitsare 0,theresultis 0.Otherwise,it's 1.5|3gives 7( 0101|0011gives 0111)
(bit-wiseXOR)
BitwiseXORofthenumbers:ifbothbits( 1or0)arethesame,theresultis 0.Otherwise,it's 1.5^3gives 6( O101^0011gives 0110)
~(bit-wiseinvert)
Thebit-wiseinversionofxis-(x+1)~5gives -6.Moredetailsathttp://stackoverflow.com/a/11810203
<(lessthan)
Returnswhetherxislessthany.Allcomparisonoperatorsreturn Trueor False.Notethecapitalizationofthesenames.5<3gives Falseand 3<5gives True.Comparisonscanbechainedarbitrarily: 3<5<7gives True.
>(greaterthan)
Returnswhetherxisgreaterthany5>3returns True.Ifbothoperandsarenumbers,theyarefirstconvertedtoacommontype.Otherwise,italwaysreturns False.
<=(lessthanorequalto)
Returnswhetherxislessthanorequaltoyx=3;y=6;x<=yreturns True
>=(greaterthanorequalto)
Returnswhetherxisgreaterthanorequaltoyx=4;y=3;x>=3returns True
==(equalto)
Comparesiftheobjectsareequalx=2;y=2;x==yreturns Truex='str';y='stR';x==yreturns Falsex='str';y='str';x==yreturns True
!=(notequalto)
Comparesiftheobjectsarenotequalx=2;y=3;x!=yreturns True
not(booleanNOT)
OperatorsandExpressions
35
Ifxis True,itreturns False.Ifxis False,itreturns True.x=True;notxreturns False.
and(booleanAND)
xandyreturns Falseifxis False,elseitreturnsevaluationofyx=False;y=True;xandyreturns FalsesincexisFalse.Inthiscase,Pythonwillnotevaluateysinceitknowsthatthelefthandsideofthe'and'expressionis Falsewhichimpliesthatthewholeexpressionwillbe Falseirrespectiveoftheothervalues.Thisiscalledshort-circuitevaluation.
or(booleanOR)
Ifxis True,itreturnsTrue,elseitreturnsevaluationofyx=True;y=False;xoryreturns True.Short-circuitevaluationapplieshereaswell.
ShortcutformathoperationandassignmentItiscommontorunamathoperationonavariableandthenassigntheresultoftheoperationbacktothevariable,hencethereisashortcutforsuchexpressions:
a=2
a=a*3
canbewrittenas:
a=2
a*=3
Noticethat var=varoperationexpressionbecomes varoperation=expression.
EvaluationOrder
Ifyouhadanexpressionsuchas 2+3*4,istheadditiondonefirstorthemultiplication?Ourhighschoolmathstellsusthatthemultiplicationshouldbedonefirst.Thismeansthatthemultiplicationoperatorhashigherprecedencethantheadditionoperator.
ThefollowingtablegivestheprecedencetableforPython,fromthelowestprecedence(leastbinding)tothehighestprecedence(mostbinding).Thismeansthatinagivenexpression,Pythonwillfirstevaluatetheoperatorsandexpressionslowerinthetablebeforetheoneslistedhigherinthetable.
Thefollowingtable,takenfromthePythonreferencemanual,isprovidedforthesakeofcompleteness.Itisfarbettertouseparenthesestogroupoperatorsandoperandsappropriatelyinordertoexplicitlyspecifytheprecedence.Thismakestheprogrammorereadable.SeeChangingtheOrderofEvaluationbelowfordetails.
lambda:LambdaExpressionif-else:Conditionalexpressionor:BooleanORand:BooleanANDnotx:BooleanNOTin,notin,is,isnot,<,<=,>,>=,!=,==:Comparisons,includingmembershiptestsandidentitytests|:BitwiseOR :BitwiseXOR&:BitwiseAND<<,>>:Shifts
OperatorsandExpressions
36
+,-:Additionandsubtraction*,/,//,%:Multiplication,Division,FloorDivisionandRemainder+x,-x,~x:Positive,Negative,bitwiseNOT**:Exponentiationx[index],x[index:index],x(arguments...),x.attribute:Subscription,slicing,call,attributereference(expressions...),[expressions...],{key:value...},{expressions...}:Bindingortupledisplay,listdisplay,dictionarydisplay,setdisplay
Theoperatorswhichwehavenotalreadycomeacrosswillbeexplainedinlaterchapters.
Operatorswiththesameprecedencearelistedinthesamerowintheabovetable.Forexample, +and -havethesameprecedence.
ChangingtheOrderOfEvaluationTomaketheexpressionsmorereadable,wecanuseparentheses.Forexample, 2+(3*4)isdefinitelyeasiertounderstandthan 2+3*4whichrequiresknowledgeoftheoperatorprecedences.Aswitheverythingelse,theparenthesesshouldbeusedreasonably(donotoverdoit)andshouldnotberedundant,asin (2+(3*4)).
Thereisanadditionaladvantagetousingparentheses-ithelpsustochangetheorderofevaluation.Forexample,ifyouwantadditiontobeevaluatedbeforemultiplicationinanexpression,thenyoucanwritesomethinglike (2+3)*4.
Associativity
Operatorsareusuallyassociatedfromlefttoright.Thismeansthatoperatorswiththesameprecedenceareevaluatedinalefttorightmanner.Forexample, 2+3+4isevaluatedas (2+3)+4.
Expressions
Example(saveas expression.py):
length=5
breadth=2
area=length*breadth
print('Areais',area)
print('Perimeteris',2*(length+breadth))
Output:
$pythonexpression.py
Areais10
Perimeteris14
HowItWorks
Thelengthandbreadthoftherectanglearestoredinvariablesbythesamename.Weusethesetocalculatetheareaandperimeteroftherectanglewiththehelpofexpressions.Westoretheresultoftheexpression length*breadthinthevariable areaandthenprintitusingthe printfunction.Inthesecondcase,wedirectlyusethevalueoftheexpression 2*(length+breadth)intheprintfunction.
OperatorsandExpressions
37
Also,noticehowPythonpretty-printstheoutput.Eventhoughwehavenotspecifiedaspacebetween 'Areais'andthevariable area,Pythonputsitforussothatwegetacleanniceoutputandtheprogramismuchmorereadablethisway(sincewedon'tneedtoworryaboutspacinginthestringsweuseforoutput).ThisisanexampleofhowPythonmakeslifeeasyfortheprogrammer.
Summary
Wehaveseenhowtouseoperators,operandsandexpressions-thesearethebasicbuildingblocksofanyprogram.Next,wewillseehowtomakeuseoftheseinourprogramsusingstatements.
OperatorsandExpressions
38
ControlFlowIntheprogramswehaveseentillnow,therehasalwaysbeenaseriesofstatementsfaithfullyexecutedbyPythoninexacttop-downorder.Whatifyouwantedtochangetheflowofhowitworks?Forexample,youwanttheprogramtotakesomedecisionsanddodifferentthingsdependingondifferentsituations,suchasprinting'GoodMorning'or'GoodEvening'dependingonthetimeoftheday?
Asyoumighthaveguessed,thisisachievedusingcontrolflowstatements.TherearethreecontrolflowstatementsinPython-if, forand while.
The ifstatement
The ifstatementisusedtocheckacondition:iftheconditionistrue,werunablockofstatements(calledtheif-block),elseweprocessanotherblockofstatements(calledtheelse-block).Theelseclauseisoptional.
Example(saveas if.py):
number=23
guess=int(input('Enteraninteger:'))
ifguess==number:
#Newblockstartshere
print('Congratulations,youguessedit.')
print('(butyoudonotwinanyprizes!)')
#Newblockendshere
elifguess<number:
#Anotherblock
print('No,itisalittlehigherthanthat')
#Youcandowhateveryouwantinablock...
else:
print('No,itisalittlelowerthanthat')
#youmusthaveguessed>numbertoreachhere
print('Done')
#Thislaststatementisalwaysexecuted,
#aftertheifstatementisexecuted.
Output:
$pythonif.py
Enteraninteger:50
No,itisalittlelowerthanthat
Done
$pythonif.py
Enteraninteger:22
No,itisalittlehigherthanthat
Done
$pythonif.py
Enteraninteger:23
Congratulations,youguessedit.
(butyoudonotwinanyprizes!)
Done
HowItWorks
Controlflow
39
Inthisprogram,wetakeguessesfromtheuserandcheckifitisthenumberthatwehave.Wesetthevariable numbertoanyintegerwewant,say 23.Then,wetaketheuser'sguessusingthe input()function.Functionsarejustreusablepiecesofprograms.We'llreadmoreabouttheminthenextchapter.
Wesupplyastringtothebuilt-in inputfunctionwhichprintsittothescreenandwaitsforinputfromtheuser.Onceweentersomethingandpresskbd:[enter]key,the input()functionreturnswhatweentered,asastring.Wethenconvertthisstringtoanintegerusing intandthenstoreitinthevariable guess.Actually,the intisaclassbutallyouneedtoknowrightnowisthatyoucanuseittoconvertastringtoaninteger(assumingthestringcontainsavalidintegerinthetext).
Next,wecomparetheguessoftheuserwiththenumberwehavechosen.Iftheyareequal,weprintasuccessmessage.NoticethatweuseindentationlevelstotellPythonwhichstatementsbelongtowhichblock.ThisiswhyindentationissoimportantinPython.Ihopeyouarestickingtothe"consistentindentation"rule.Areyou?
Noticehowthe ifstatementcontainsacolonattheend-weareindicatingtoPythonthatablockofstatementsfollows.
Then,wecheckiftheguessislessthanthenumber,andifso,weinformtheuserthattheymustguessalittlehigherthanthat.Whatwehaveusedhereisthe elifclausewhichactuallycombinestworelated ifelse-ifelsestatementsintoonecombined if-elif-elsestatement.Thismakestheprogrameasierandreducestheamountofindentationrequired.
The elifand elsestatementsmustalsohaveacolonattheendofthelogicallinefollowedbytheircorrespondingblockofstatements(withproperindentation,ofcourse)
Youcanhaveanother ifstatementinsidetheif-blockofan ifstatementandsoon-thisiscalledanested ifstatement.
Rememberthatthe elifand elsepartsareoptional.Aminimalvalid ifstatementis:
ifTrue:
print('Yes,itistrue')
AfterPythonhasfinishedexecutingthecomplete ifstatementalongwiththeassociated elifand elseclauses,itmovesontothenextstatementintheblockcontainingthe ifstatement.Inthiscase,itisthemainblock(whereexecutionoftheprogramstarts),andthenextstatementisthe print('Done')statement.Afterthis,Pythonseestheendsoftheprogramandsimplyfinishesup.
Eventhoughthisisaverysimpleprogram,Ihavebeenpointingoutalotofthingsthatyoushouldnotice.Alltheseareprettystraightforward(andsurprisinglysimpleforthoseofyoufromC/C++backgrounds).Youwillneedtobecomeawareofallthesethingsinitially,butaftersomepracticeyouwillbecomecomfortablewiththem,anditwillallfeel'natural'toyou.
NoteforC/C++Programmers
Thereisno switchstatementinPython.Youcanusean if..elif..elsestatementtodothesamething(andinsomecases,useadictionarytodoitquickly)
ThewhileStatementThe whilestatementallowsyoutorepeatedlyexecuteablockofstatementsaslongasaconditionistrue.A whilestatementisanexampleofwhatiscalledaloopingstatement.A whilestatementcanhaveanoptional elseclause.
Example(saveas while.py):
number=23
running=True
whilerunning:
guess=int(input('Enteraninteger:'))
ifguess==number:
print('Congratulations,youguessedit.')
Controlflow
40
#thiscausesthewhilelooptostop
running=False
elifguess<number:
print('No,itisalittlehigherthanthat.')
else:
print('No,itisalittlelowerthanthat.')
else:
print('Thewhileloopisover.')
#Doanythingelseyouwanttodohere
print('Done')
Output:
$pythonwhile.py
Enteraninteger:50
No,itisalittlelowerthanthat.
Enteraninteger:22
No,itisalittlehigherthanthat.
Enteraninteger:23
Congratulations,youguessedit.
Thewhileloopisover.
Done
HowItWorks
Inthisprogram,wearestillplayingtheguessinggame,buttheadvantageisthattheuserisallowedtokeepguessinguntilheguessescorrectly-thereisnoneedtorepeatedlyruntheprogramforeachguess,aswehavedoneintheprevioussection.Thisaptlydemonstratestheuseofthe whilestatement.
Wemovethe inputand ifstatementstoinsidethe whileloopandsetthevariable runningto Truebeforethewhileloop.First,wecheckifthevariable runningis Trueandthenproceedtoexecutethecorrespondingwhile-block.Afterthisblockisexecuted,theconditionisagaincheckedwhichinthiscaseisthe runningvariable.Ifitistrue,weexecutethewhile-blockagain,elsewecontinuetoexecutetheoptionalelse-blockandthencontinuetothenextstatement.
The elseblockisexecutedwhenthe whileloopconditionbecomes False-thismayevenbethefirsttimethattheconditionischecked.Ifthereisan elseclausefora whileloop,itisalwaysexecutedunlessyoubreakoutoftheloopwithabreakstatement.
The Trueand FalsearecalledBooleantypesandyoucanconsiderthemtobeequivalenttothevalue 1and 0respectively.
NoteforC/C++Programmers
Rememberthatyoucanhavean elseclauseforthe whileloop.
The forloopThe for..instatementisanotherloopingstatementwhichiteratesoverasequenceofobjectsi.e.gothrougheachiteminasequence.Wewillseemoreaboutsequencesindetailinlaterchapters.Whatyouneedtoknowrightnowisthatasequenceisjustanorderedcollectionofitems.
Example(saveas for.py):
foriinrange(1,5):
print(i)
else:
print('Theforloopisover')
Controlflow
41
Output:
$pythonfor.py
1
2
3
4
Theforloopisover
HowItWorks
Inthisprogram,weareprintingasequenceofnumbers.Wegeneratethissequenceofnumbersusingthebuilt-in rangefunction.
Whatwedohereissupplyittwonumbersand rangereturnsasequenceofnumbersstartingfromthefirstnumberanduptothesecondnumber.Forexample, range(1,5)givesthesequence [1,2,3,4].Bydefault, rangetakesastepcountof1.Ifwesupplyathirdnumberto range,thenthatbecomesthestepcount.Forexample, range(1,5,2)gives [1,3].Rememberthattherangeextendsuptothesecondnumberi.e.itdoesnotincludethesecondnumber.
Notethat range()generatesonlyonenumberatatime,ifyouwantthefulllistofnumbers,call list()onthe range(),forexample, list(range(5))willresultin [0,1,2,3,4].Listsareexplainedinthedatastructureschapter.
The forlooptheniteratesoverthisrange- foriinrange(1,5)isequivalentto foriin[1,2,3,4]whichislikeassigningeachnumber(orobject)inthesequencetoi,oneatatime,andthenexecutingtheblockofstatementsforeachvalueofi.Inthiscase,wejustprintthevalueintheblockofstatements.
Rememberthatthe elsepartisoptional.Whenincluded,itisalwaysexecutedonceafterthe forloopisoverunlessabreakstatementisencountered.
Rememberthatthe for..inloopworksforanysequence.Here,wehavealistofnumbersgeneratedbythebuilt-in rangefunction,butingeneralwecanuseanykindofsequenceofanykindofobjects!Wewillexplorethisideaindetailinlaterchapters.
NoteforC/C++/Java/C#Programmers
ThePython forloopisradicallydifferentfromtheC/C++ forloop.C#programmerswillnotethatthe forloopinPythonissimilartothe foreachloopinC#.Javaprogrammerswillnotethatthesameissimilarto for(inti:IntArray)inJava1.5.
InC/C++,ifyouwanttowrite for(inti=0;i<5;i++),theninPythonyouwritejust foriinrange(0,5).Asyoucansee,the forloopissimpler,moreexpressiveandlesserrorproneinPython.
ThebreakStatement
The breakstatementisusedtobreakoutofaloopstatementi.e.stoptheexecutionofaloopingstatement,eveniftheloopconditionhasnotbecome Falseorthesequenceofitemshasnotbeencompletelyiteratedover.
Animportantnoteisthatifyoubreakoutofa foror whileloop,anycorrespondingloop elseblockisnotexecuted.
Example(saveas break.py):
whileTrue:
s=input('Entersomething:')
ifs=='quit':
break
print('Lengthofthestringis',len(s))
print('Done')
Controlflow
42
Output:
$pythonbreak.py
Entersomething:Programmingisfun
Lengthofthestringis18
Entersomething:Whentheworkisdone
Lengthofthestringis21
Entersomething:ifyouwannamakeyourworkalsofun:
Lengthofthestringis37
Entersomething:usePython!
Lengthofthestringis11
Entersomething:quit
Done
HowItWorks
Inthisprogram,werepeatedlytaketheuser'sinputandprintthelengthofeachinputeachtime.Weareprovidingaspecialconditiontostoptheprogrambycheckingiftheuserinputis 'quit'.Westoptheprogrambybreakingoutoftheloopandreachtheendoftheprogram.
Thelengthoftheinputstringcanbefoundoutusingthebuilt-in lenfunction.
Rememberthatthe breakstatementcanbeusedwiththe forloopaswell.
Swaroop'sPoeticPython
TheinputIhaveusedhereisaminipoemIhavewritten:
Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
The continueStatementThe continuestatementisusedtotellPythontoskiptherestofthestatementsinthecurrentloopblockandtocontinuetothenextiterationoftheloop.
Example(saveas continue.py):
whileTrue:
s=input('Entersomething:')
ifs=='quit':
break
iflen(s)<3:
print('Toosmall')
continue
print('Inputisofsufficientlength')
#Dootherkindsofprocessinghere...
Output:
$pythoncontinue.py
Entersomething:a
Toosmall
Entersomething:12
Toosmall
Entersomething:abc
Inputisofsufficientlength
Entersomething:quit
Controlflow
43
HowItWorks
Inthisprogram,weacceptinputfromtheuser,butweprocesstheinputstringonlyifitisatleast3characterslong.So,weusethebuilt-in lenfunctiontogetthelengthandifthelengthislessthan3,weskiptherestofthestatementsintheblockbyusingthecontinuestatement.Otherwise,therestofthestatementsintheloopareexecuted,doinganykindofprocessingwewanttodohere.
Notethatthe continuestatementworkswiththe forloopaswell.
Summary
Wehaveseenhowtousethethreecontrolflowstatements- if, whileand foralongwiththeirassociated breakandcontinuestatements.ThesearesomeofthemostcommonlyusedpartsofPythonandhence,becomingcomfortablewiththemisessential.
Next,wewillseehowtocreateandusefunctions.
Controlflow
44
FunctionsFunctionsarereusablepiecesofprograms.Theyallowyoutogiveanametoablockofstatements,allowingyoutorunthatblockusingthespecifiednameanywhereinyourprogramandanynumberoftimes.Thisisknownascallingthefunction.Wehavealreadyusedmanybuilt-infunctionssuchas lenand range.
Thefunctionconceptisprobablythemostimportantbuildingblockofanynon-trivialsoftware(inanyprogramminglanguage),sowewillexplorevariousaspectsoffunctionsinthischapter.
Functionsaredefinedusingthe defkeyword.Afterthiskeywordcomesanidentifiernameforthefunction,followedbyapairofparentheseswhichmayenclosesomenamesofvariables,andbythefinalcolonthatendstheline.Nextfollowstheblockofstatementsthatarepartofthisfunction.Anexamplewillshowthatthisisactuallyverysimple:
Example(saveas function1.py):
defsay_hello():
#blockbelongingtothefunction
print('helloworld')
#Endoffunction
say_hello()#callthefunction
say_hello()#callthefunctionagain
Output:
$pythonfunction1.py
helloworld
helloworld
HowItWorks
Wedefineafunctioncalled say_hellousingthesyntaxasexplainedabove.Thisfunctiontakesnoparametersandhencetherearenovariablesdeclaredintheparentheses.Parameterstofunctionsarejustinputtothefunctionsothatwecanpassindifferentvaluestoitandgetbackcorrespondingresults.
Noticethatwecancallthesamefunctiontwicewhichmeanswedonothavetowritethesamecodeagain.
FunctionParameters
Afunctioncantakeparameters,whicharevaluesyousupplytothefunctionsothatthefunctioncandosomethingutilisingthosevalues.Theseparametersarejustlikevariablesexceptthatthevaluesofthesevariablesaredefinedwhenwecallthefunctionandarealreadyassignedvalueswhenthefunctionruns.
Parametersarespecifiedwithinthepairofparenthesesinthefunctiondefinition,separatedbycommas.Whenwecallthefunction,wesupplythevaluesinthesameway.Notetheterminologyused-thenamesgiveninthefunctiondefinitionarecalledparameterswhereasthevaluesyousupplyinthefunctioncallarecalledarguments.
Example(saveas function_param.py):
defprint_max(a,b):
ifa>b:
print(a,'ismaximum')
elifa==b:
print(a,'isequalto',b)
else:
Functions
45
print(b,'ismaximum')
#directlypassliteralvalues
print_max(3,4)
x=5
y=7
#passvariablesasarguments
print_max(x,y)
Output:
$pythonfunction_param.py
4ismaximum
7ismaximum
HowItWorks
Here,wedefineafunctioncalled print_maxthatusestwoparameterscalled aand b.Wefindoutthegreaternumberusingasimple if..elsestatementandthenprintthebiggernumber.
Thefirsttimewecallthefunction print_max,wedirectlysupplythenumbersasarguments.Inthesecondcase,wecallthefunctionwithvariablesasarguments. print_max(x,y)causesthevalueofargument xtobeassignedtoparameter aandthevalueofargument ytobeassignedtoparameter b.The print_maxfunctionworksthesamewayinbothcases.
LocalVariablesWhenyoudeclarevariablesinsideafunctiondefinition,theyarenotrelatedinanywaytoothervariableswiththesamenamesusedoutsidethefunction-i.e.variablenamesarelocaltothefunction.Thisiscalledthescopeofthevariable.Allvariableshavethescopeoftheblocktheyaredeclaredinstartingfromthepointofdefinitionofthename.
Example(saveas function_local.py):
x=50
deffunc(x):
print('xis',x)
x=2
print('Changedlocalxto',x)
func(x)
print('xisstill',x)
Output:
$pythonfunction_local.py
xis50
Changedlocalxto2
xisstill50
HowItWorks
Thefirsttimethatweprintthevalueofthenamexwiththefirstlineinthefunction'sbody,Pythonusesthevalueoftheparameterdeclaredinthemainblock,abovethefunctiondefinition.
Functions
46
Next,weassignthevalue 2to x.Thename xislocaltoourfunction.So,whenwechangethevalueof xinthefunction,the xdefinedinthemainblockremainsunaffected.
Withthelast printstatement,wedisplaythevalueof xasdefinedinthemainblock,therebyconfirmingthatitisactuallyunaffectedbythelocalassignmentwithinthepreviouslycalledfunction.
The globalstatement
Ifyouwanttoassignavaluetoanamedefinedatthetopleveloftheprogram(i.e.notinsideanykindofscopesuchasfunctionsorclasses),thenyouhavetotellPythonthatthenameisnotlocal,butitisglobal.Wedothisusingthe globalstatement.Itisimpossibletoassignavaluetoavariabledefinedoutsideafunctionwithoutthe globalstatement.
Youcanusethevaluesofsuchvariablesdefinedoutsidethefunction(assumingthereisnovariablewiththesamenamewithinthefunction).However,thisisnotencouragedandshouldbeavoidedsinceitbecomesuncleartothereaderoftheprogramastowherethatvariable'sdefinitionis.Usingthe globalstatementmakesitamplyclearthatthevariableisdefinedinanoutermostblock.
Example(saveas function_global.py):
x=50
deffunc():
globalx
print('xis',x)
x=2
print('Changedglobalxto',x)
func()
print('Valueofxis',x)
Output:
$pythonfunction_global.py
xis50
Changedglobalxto2
Valueofxis2
HowItWorks
The globalstatementisusedtodeclarethat xisaglobalvariable-hence,whenweassignavalueto xinsidethefunction,thatchangeisreflectedwhenweusethevalueof xinthemainblock.
Youcanspecifymorethanoneglobalvariableusingthesame globalstatemente.g. globalx,y,z.
DefaultArgumentValues
Forsomefunctions,youmaywanttomakesomeparametersoptionalandusedefaultvaluesincasetheuserdoesnotwanttoprovidevaluesforthem.Thisisdonewiththehelpofdefaultargumentvalues.Youcanspecifydefaultargumentvaluesforparametersbyappendingtotheparameternameinthefunctiondefinitiontheassignmentoperator( =)followedbythedefaultvalue.
Notethatthedefaultargumentvalueshouldbeaconstant.Moreprecisely,thedefaultargumentvalueshouldbeimmutable-thisisexplainedindetailinlaterchapters.Fornow,justrememberthis.
Functions
47
Example(saveas function_default.py):
defsay(message,times=1):
print(message*times)
say('Hello')
say('World',5)
Output:
$pythonfunction_default.py
Hello
WorldWorldWorldWorldWorld
HowItWorks
Thefunctionnamed sayisusedtoprintastringasmanytimesasspecified.Ifwedon'tsupplyavalue,thenbydefault,thestringisprintedjustonce.Weachievethisbyspecifyingadefaultargumentvalueof 1totheparameter times.
Inthefirstusageof say,wesupplyonlythestringanditprintsthestringonce.Inthesecondusageof say,wesupplyboththestringandanargument 5statingthatwewanttosaythestringmessage5times.
CAUTION
Onlythoseparameterswhichareattheendoftheparameterlistcanbegivendefaultargumentvaluesi.e.youcannothaveaparameterwithadefaultargumentvalueprecedingaparameterwithoutadefaultargumentvalueinthefunction'sparameterlist.
Thisisbecausethevaluesareassignedtotheparametersbyposition.Forexample, deffunc(a,b=5)isvalid,but deffunc(a=5,b)isnotvalid.
KeywordArguments
Ifyouhavesomefunctionswithmanyparametersandyouwanttospecifyonlysomeofthem,thenyoucangivevaluesforsuchparametersbynamingthem-thisiscalledkeywordarguments-weusethename(keyword)insteadoftheposition(whichwehavebeenusingallalong)tospecifytheargumentstothefunction.
Therearetwoadvantages-one,usingthefunctioniseasiersincewedonotneedtoworryabouttheorderofthearguments.Two,wecangivevaluestoonlythoseparameterstowhichwewantto,providedthattheotherparametershavedefaultargumentvalues.
Example(saveas function_keyword.py):
deffunc(a,b=5,c=10):
print('ais',a,'andbis',b,'andcis',c)
func(3,7)
func(25,c=24)
func(c=50,a=100)
Output:
$pythonfunction_keyword.py
ais3andbis7andcis10
ais25andbis5andcis24
ais100andbis5andcis50
Functions
48
HowItWorks
Thefunctionnamed funchasoneparameterwithoutadefaultargumentvalue,followedbytwoparameterswithdefaultargumentvalues.
Inthefirstusage, func(3,7),theparameter agetsthevalue 3,theparameter bgetsthevalue 7and cgetsthedefaultvalueof 10.
Inthesecondusage func(25,c=24),thevariable agetsthevalueof25duetothepositionoftheargument.Then,theparameter cgetsthevalueof 24duetonamingi.e.keywordarguments.Thevariable bgetsthedefaultvalueof 5.
Inthethirdusage func(c=50,a=100),weusekeywordargumentsforallspecifiedvalues.Noticethatwearespecifyingthevalueforparameter cbeforethatfor aeventhough aisdefinedbefore cinthefunctiondefinition.
VarArgsparametersSometimesyoumightwanttodefineafunctionthatcantakeanynumberofparameters,i.e.variablenumberofarguments,thiscanbeachievedbyusingthestars(saveas function_varargs.py):
deftotal(a=5,*numbers,**phonebook):
print('a',a)
#iteratethroughalltheitemsintuple
forsingle_iteminnumbers:
print('single_item',single_item)
#iteratethroughalltheitemsindictionary
forfirst_part,second_partinphonebook.items():
print(first_part,second_part)
total(10,1,2,3,Jack=1123,John=2231,Inge=1560)
Output:
$pythonfunction_varargs.py
a10
single_item1
single_item2
single_item3
Inge1560
John2231
Jack1123
HowItWorks
Whenwedeclareastarredparametersuchas *param,thenallthepositionalargumentsfromthatpointtilltheendarecollectedasatuplecalled'param'.
Similarly,whenwedeclareadouble-starredparametersuchas **param,thenallthekeywordargumentsfromthatpointtilltheendarecollectedasadictionarycalled'param'.
Wewillexploretuplesanddictionariesinalaterchapter.
The returnstatement
The returnstatementisusedtoreturnfromafunctioni.e.breakoutofthefunction.Wecanoptionallyreturnavaluefromthefunctionaswell.
Functions
49
Example(saveas function_return.py):
defmaximum(x,y):
ifx>y:
returnx
elifx==y:
return'Thenumbersareequal'
else:
returny
print(maximum(2,3))
Output:
$pythonfunction_return.py
3
HowItWorks
The maximumfunctionreturnsthemaximumoftheparameters,inthiscasethenumberssuppliedtothefunction.Itusesasimpleif..elsestatementtofindthegreatervalueandthenreturnsthatvalue.
Notethata returnstatementwithoutavalueisequivalentto returnNone. NoneisaspecialtypeinPythonthatrepresentsnothingness.Forexample,itisusedtoindicatethatavariablehasnovalueifithasavalueof None.
Everyfunctionimplicitlycontainsa returnNonestatementattheendunlessyouhavewrittenyourown returnstatement.Youcanseethisbyrunning print(some_function())wherethefunction some_functiondoesnotusethe returnstatementsuchas:
defsome_function():
pass
The passstatementisusedinPythontoindicateanemptyblockofstatements.
TIP:Thereisabuilt-infunctioncalled maxthatalreadyimplementsthe'findmaximum'functionality,sousethisbuilt-infunctionwheneverpossible.
DocStringsPythonhasaniftyfeaturecalleddocumentationstrings,usuallyreferredtobyitsshorternamedocstrings.DocStringsareanimportanttoolthatyoushouldmakeuseofsinceithelpstodocumenttheprogrambetterandmakesiteasiertounderstand.Amazingly,wecanevengetthedocstringbackfrom,sayafunction,whentheprogramisactuallyrunning!
Example(saveas function_docstring.py):
defprint_max(x,y):
'''Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.'''
#converttointegers,ifpossible
x=int(x)
y=int(y)
ifx>y:
print(x,'ismaximum')
else:
print(y,'ismaximum')
Functions
50
print_max(3,5)
print(print_max.__doc__)
Output:
$pythonfunction_docstring.py
5ismaximum
Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.
HowItWorks
Astringonthefirstlogicallineofafunctionisthedocstringforthatfunction.NotethatDocStringsalsoapplytomodulesandclasseswhichwewilllearnaboutintherespectivechapters.
Theconventionfollowedforadocstringisamulti-linestringwherethefirstlinestartswithacapitalletterandendswithadot.Thenthesecondlineisblankfollowedbyanydetailedexplanationstartingfromthethirdline.Youarestronglyadvisedtofollowthisconventionforallyourdocstringsforallyournon-trivialfunctions.
Wecanaccessthedocstringofthe print_maxfunctionusingthe __doc__(noticethedoubleunderscores)attribute(namebelongingto)ofthefunction.JustrememberthatPythontreatseverythingasanobjectandthisincludesfunctions.We'lllearnmoreaboutobjectsinthechapteronclasses.
Ifyouhaveused help()inPython,thenyouhavealreadyseentheusageofdocstrings!Whatitdoesisjustfetchthe __doc__attributeofthatfunctionanddisplaysitinaneatmannerforyou.Youcantryitoutonthefunctionabove-justincludehelp(print_max)inyourprogram.Remembertopressthe qkeytoexit help.
Automatedtoolscanretrievethedocumentationfromyourprograminthismanner.Therefore,Istronglyrecommendthatyouusedocstringsforanynon-trivialfunctionthatyouwrite.The pydoccommandthatcomeswithyourPythondistributionworkssimilarlyto help()usingdocstrings.
Summary
Wehaveseensomanyaspectsoffunctionsbutnotethatwestillhaven'tcoveredallaspectsofthem.However,wehavealreadycoveredmostofwhatyou'lluseregardingPythonfunctionsonaneverydaybasis.
Next,wewillseehowtouseaswellascreatePythonmodules.
Functions
51
ModulesYouhaveseenhowyoucanreusecodeinyourprogrambydefiningfunctionsonce.Whatifyouwantedtoreuseanumberoffunctionsinotherprogramsthatyouwrite?Asyoumighthaveguessed,theanswerismodules.
Therearevariousmethodsofwritingmodules,butthesimplestwayistocreateafilewitha .pyextensionthatcontainsfunctionsandvariables.
AnothermethodistowritethemodulesinthenativelanguageinwhichthePythoninterpreteritselfwaswritten.Forexample,youcanwritemodulesintheCprogramminglanguageandwhencompiled,theycanbeusedfromyourPythoncodewhenusingthestandardPythoninterpreter.
Amodulecanbeimportedbyanotherprogramtomakeuseofitsfunctionality.ThisishowwecanusethePythonstandardlibraryaswell.First,wewillseehowtousethestandardlibrarymodules.
Example(saveas module_using_sys.py):
importsys
print('Thecommandlineargumentsare:')
foriinsys.argv:
print(i)
print('\n\nThePYTHONPATHis',sys.path,'\n')
Output:
$pythonmodule_using_sys.pywearearguments#eachargisseparatedbywhitespace
Thecommandlineargumentsare:
module_using_sys.py
we
are
arguments
ThePYTHONPATHis['/tmp/py',
#manyentrieshere,notshownhere
'/Library/Python/2.7/site-packages',
'/usr/local/lib/python2.7/site-packages']
HowItWorks
First,weimportthe sysmoduleusingthe importstatement.Basically,thistranslatestoustellingPythonthatwewanttousethismodule.The sysmodulecontainsfunctionalityrelatedtothePythoninterpreteranditsenvironmenti.e.thesystem.
WhenPythonexecutesthe importsysstatement,itlooksforthe sysmodule.Inthiscase,itisoneofthebuilt-inmodules,andhencePythonknowswheretofindit.
Ifitwasnotacompiledmodulei.e.amodulewritteninPython,thenthePythoninterpreterwillsearchforitinthedirectorieslistedinits sys.pathvariable.Ifthemoduleisfound,thenthestatementsinthebodyofthatmodulearerunandthemoduleismadeavailableforyoutouse.Notethattheinitializationisdoneonlythefirsttimethatweimportamodule.
The argvvariableinthe sysmoduleisaccessedusingthedottednotationi.e. sys.argv.Itclearlyindicatesthatthisnameispartofthe sysmodule.Anotheradvantageofthisapproachisthatthenamedoesnotclashwithany argvvariableusedinyourprogram.
Modules
52
The sys.argvvariableisalistofstrings(listsareexplainedindetailinalaterchapter).Specifically,the sys.argvcontainsthelistofcommandlineargumentsi.e.theargumentspassedtoyourprogramusingthecommandline.
IfyouareusinganIDEtowriteandruntheseprograms,lookforawaytospecifycommandlineargumentstotheprograminthemenus.
Here,whenweexecute pythonmodule_using_sys.pywearearguments,werunthemodule module_using_sys.pywiththepythoncommandandtheotherthingsthatfollowareargumentspassedtotheprogram.Pythonstoresthecommandlineargumentsinthe sys.argvvariableforustouse.
Remember,thenameofthescriptrunningisalwaysthefirstelementinthe sys.argvlist.So,inthiscasewewillhave'module_using_sys.py'as sys.argv[0], 'we'as sys.argv[1], 'are'as sys.argv[2]and 'arguments'assys.argv[3].NoticethatPythonstartscountingfrom0andnot1.
The sys.pathcontainsthelistofdirectorynameswheremodulesareimportedfrom.Observethatthefirststringin sys.pathisempty-thisemptystringindicatesthatthecurrentdirectoryisalsopartofthe sys.pathwhichissameasthe PYTHONPATHenvironmentvariable.Thismeansthatyoucandirectlyimportmoduleslocatedinthecurrentdirectory.Otherwise,youwillhavetoplaceyourmoduleinoneofthedirectorieslistedin sys.path.
Notethatthecurrentdirectoryisthedirectoryfromwhichtheprogramislaunched.Run importos;print(os.getcwd())tofindoutthecurrentdirectoryofyourprogram.
Byte-compiled.pycfiles
Importingamoduleisarelativelycostlyaffair,soPythondoessometrickstomakeitfaster.Onewayistocreatebyte-compiledfileswiththeextension .pycwhichisanintermediateformthatPythontransformstheprograminto(remembertheintroductionsectiononhowPythonworks?).This .pycfileisusefulwhenyouimportthemodulethenexttimefromadifferentprogram-itwillbemuchfastersinceaportionoftheprocessingrequiredinimportingamoduleisalreadydone.Also,thesebyte-compiledfilesareplatform-independent.
NOTE:These .pycfilesareusuallycreatedinthesamedirectoryasthecorresponding .pyfiles.IfPythondoesnothavepermissiontowritetofilesinthatdirectory,thenthe .pycfileswillnotbecreated.
Thefrom..importstatement
Ifyouwanttodirectlyimportthe argvvariableintoyourprogram(toavoidtypingthe sys.everytimeforit),thenyoucanusethe fromsysimportargvstatement.
WARNING:Ingeneral,avoidusingthe from..importstatement,usethe importstatementinstead.Thisisbecauseyourprogramwillavoidnameclashesandwillbemorereadable.
Example:
frommathimportsqrt
print("Squarerootof16is",sqrt(16))
Amodule's __name__
Everymodulehasanameandstatementsinamodulecanfindoutthenameoftheirmodule.Thisishandyfortheparticularpurposeoffiguringoutwhetherthemoduleisbeingrunstandaloneorbeingimported.Asmentionedpreviously,whenamoduleisimportedforthefirsttime,thecodeitcontainsgetsexecuted.Wecanusethistomakethemodulebehaveindifferentways
Modules
53
dependingonwhetheritisbeingusedbyitselforbeingimportedfromanothermodule.Thiscanbeachievedusingthe__name__attributeofthemodule.
Example(saveas module_using_name.py):
if__name__=='__main__':
print('Thisprogramisbeingrunbyitself')
else:
print('Iambeingimportedfromanothermodule')
Output:
$pythonmodule_using_name.py
Thisprogramisbeingrunbyitself
$python
>>>importmodule_using_name
Iambeingimportedfromanothermodule
>>>
HowItWorks
EveryPythonmodulehasits __name__defined.Ifthisis '__main__',thatimpliesthatthemoduleisbeingrunstandalonebytheuserandwecantakeappropriateactions.
MakingYourOwnModules
Creatingyourownmodulesiseasy,you'vebeendoingitallalong!ThisisbecauseeveryPythonprogramisalsoamodule.Youjusthavetomakesureithasa .pyextension.Thefollowingexampleshouldmakeitclear.
Example(saveas mymodule.py):
defsay_hi():
print('Hi,thisismymodulespeaking.')
__version__='0.1'
Theabovewasasamplemodule.Asyoucansee,thereisnothingparticularlyspecialaboutitcomparedtoourusualPythonprogram.WewillnextseehowtousethismoduleinourotherPythonprograms.
Rememberthatthemoduleshouldbeplacedeitherinthesamedirectoryastheprogramfromwhichweimportit,orinoneofthedirectorieslistedin sys.path.
Anothermodule(saveas mymodule_demo.py):
importmymodule
mymodule.say_hi()
print('Version',mymodule.__version__)
Output:
$pythonmymodule_demo.py
Hi,thisismymodulespeaking.
Version0.1
HowItWorks
Modules
54
Noticethatweusethesamedottednotationtoaccessmembersofthemodule.Pythonmakesgoodreuseofthesamenotationtogivethedistinctive'Pythonic'feeltoitsothatwedon'thavetokeeplearningnewwaystodothings.
Hereisaversionutilisingthe from..importsyntax(saveas mymodule_demo2.py):
frommymoduleimportsay_hi,__version__
say_hi()
print('Version',__version__)
Theoutputof mymodule_demo2.pyissameastheoutputof mymodule_demo.py.
Noticethatiftherewasalreadya __version__namedeclaredinthemodulethatimportsmymodule,therewouldbeaclash.Thisisalsolikelybecauseitiscommonpracticeforeachmoduletodeclareit'sversionnumberusingthisname.Hence,itisalwaysrecommendedtopreferthe importstatementeventhoughitmightmakeyourprogramalittlelonger.
Youcouldalsouse:
frommymoduleimport*
Thiswillimportallpublicnamessuchas say_hibutwouldnotimport __version__becauseitstartswithdoubleunderscores.
WARNING:Rememberthatyoushouldavoidusingimport-star,i.e. frommymoduleimport*.
ZenofPython
OneofPython'sguidingprinciplesisthat"ExplicitisbetterthanImplicit".Run importthisinPythontolearnmore.
The dirfunctionThebuilt-in dir()functionreturnsthelistofnamesdefinedbyanobject.Iftheobjectisamodule,thislistincludesfunctions,classesandvariables,definedinsidethatmodule.
Thisfunctioncanacceptarguments.Iftheargumentisthenameofamodule,thefunctionreturnsthelistofnamesfromthatspecifiedmodule.Ifthereisnoargument,thefunctionreturnsthelistofnamesfromthecurrentmodule.
Example:
$python
>>>importsys
#getnamesofattributesinsysmodule
>>>dir(sys)
['__displayhook__','__doc__',
'argv','builtin_module_names',
'version','version_info']
#onlyfewentriesshownhere
#getnamesofattributesforcurrentmodule
>>>dir()
['__builtins__','__doc__',
'__name__','__package__','sys']
#createanewvariable'a'
>>>a=5
>>>dir()
['__builtins__','__doc__','__name__','__package__','sys','a']
#delete/removeaname
>>>dela
Modules
55
>>>dir()
['__builtins__','__doc__','__name__','__package__','sys']
HowItWorks
First,weseetheusageof dirontheimported sysmodule.Wecanseethehugelistofattributesthatitcontains.
Next,weusethe dirfunctionwithoutpassingparameterstoit.Bydefault,itreturnsthelistofattributesforthecurrentmodule.Noticethatthelistofimportedmodulesisalsopartofthislist.
Inordertoobserve dirinaction,wedefineanewvariable aandassignitavalueandthencheck dirandweobservethatthereisanadditionalvalueinthelistofthesamename.Weremovethevariable/attributeofthecurrentmoduleusingthe delstatementandthechangeisreflectedagainintheoutputofthe dirfunction.
Anoteon del:Thisstatementisusedtodeleteavariable/nameandafterthestatementhasrun,inthiscase dela,youcannolongeraccessthevariable a-itisasifitneverexistedbeforeatall.
Notethatthe dir()functionworksonanyobject.Forexample,run dir(str)fortheattributesofthe str(string)class.
Thereisalsoa vars()functionwhichcanpotentiallygiveyoutheattributesandtheirvalues,butitwillnotworkforallcases.
PackagesBynow,youmusthavestartedobservingthehierarchyoforganizingyourprograms.Variablesusuallygoinsidefunctions.Functionsandglobalvariablesusuallygoinsidemodules.Whatifyouwantedtoorganizemodules?That'swherepackagescomeintothepicture.
Packagesarejustfoldersofmoduleswithaspecial __init__.pyfilethatindicatestoPythonthatthisfolderisspecialbecauseitcontainsPythonmodules.
Let'ssayyouwanttocreateapackagecalled'world'withsubpackages'asia','africa',etc.andthesesubpackagesinturncontainmoduleslike'india','madagascar',etc.
Thisishowyouwouldstructurethefolders:
-<somefolderpresentinthesys.path>/
-world/
-__init__.py
-asia/
-__init__.py
-india/
-__init__.py
-foo.py
-africa/
-__init__.py
-madagascar/
-__init__.py
-bar.py
Packagesarejustaconveniencetoorganizemoduleshierarchically.Youwillseemanyinstancesofthisinthestandardlibrary.
SummaryJustlikefunctionsarereusablepartsofprograms,modulesarereusableprograms.Packagesareanotherhierarchytoorganizemodules.ThestandardlibrarythatcomeswithPythonisanexampleofsuchasetofpackagesandmodules.
Wehaveseenhowtousethesemodulesandcreateourownmodules.
Modules
56
DataStructuresDatastructuresarebasicallyjustthat-theyarestructureswhichcanholdsomedatatogether.Inotherwords,theyareusedtostoreacollectionofrelateddata.
Therearefourbuilt-indatastructuresinPython-list,tuple,dictionaryandset.Wewillseehowtouseeachofthemandhowtheymakelifeeasierforus.
List
A listisadatastructurethatholdsanorderedcollectionofitemsi.e.youcanstoreasequenceofitemsinalist.Thisiseasytoimagineifyoucanthinkofashoppinglistwhereyouhavealistofitemstobuy,exceptthatyouprobablyhaveeachitemonaseparatelineinyourshoppinglistwhereasinPythonyouputcommasinbetweenthem.
ThelistofitemsshouldbeenclosedinsquarebracketssothatPythonunderstandsthatyouarespecifyingalist.Onceyouhavecreatedalist,youcanadd,removeorsearchforitemsinthelist.Sincewecanaddandremoveitems,wesaythatalistisamutabledatatypei.e.thistypecanbealtered.
QuickIntroductionToObjectsAndClassesAlthoughI'vebeengenerallydelayingthediscussionofobjectsandclassestillnow,alittleexplanationisneededrightnowsothatyoucanunderstandlistsbetter.Wewillexplorethistopicindetailinalaterchapter.
Alistisanexampleofusageofobjectsandclasses.Whenweuseavariable iandassignavaluetoit,sayinteger 5toit,youcanthinkofitascreatinganobject(i.e.instance) iofclass(i.e.type) int.Infact,youcanread help(int)tounderstandthisbetter.
Aclasscanalsohavemethodsi.e.functionsdefinedforusewithrespecttothatclassonly.Youcanusethesepiecesoffunctionalityonlywhenyouhaveanobjectofthatclass.Forexample,Pythonprovidesan appendmethodforthe listclasswhichallowsyoutoaddanitemtotheendofthelist.Forexample, mylist.append('anitem')willaddthatstringtothelistmylist.Notetheuseofdottednotationforaccessingmethodsoftheobjects.
Aclasscanalsohavefieldswhicharenothingbutvariablesdefinedforusewithrespecttothatclassonly.Youcanusethesevariables/namesonlywhenyouhaveanobjectofthatclass.Fieldsarealsoaccessedbythedottednotation,forexample,mylist.field.
Example(saveas ds_using_list.py):
#Thisismyshoppinglist
shoplist=['apple','mango','carrot','banana']
print('Ihave',len(shoplist),'itemstopurchase.')
print('Theseitemsare:',end='')
foriteminshoplist:
print(item,end='')
print('\nIalsohavetobuyrice.')
shoplist.append('rice')
print('Myshoppinglistisnow',shoplist)
print('Iwillsortmylistnow')
shoplist.sort()
print('Sortedshoppinglistis',shoplist)
DataStructures
58
print('ThefirstitemIwillbuyis',shoplist[0])
olditem=shoplist[0]
delshoplist[0]
print('Iboughtthe',olditem)
print('Myshoppinglistisnow',shoplist)
Output:
$pythonds_using_list.py
Ihave4itemstopurchase.
Theseitemsare:applemangocarrotbanana
Ialsohavetobuyrice.
Myshoppinglistisnow['apple','mango','carrot','banana','rice']
Iwillsortmylistnow
Sortedshoppinglistis['apple','banana','carrot','mango','rice']
ThefirstitemIwillbuyisapple
Iboughttheapple
Myshoppinglistisnow['banana','carrot','mango','rice']
HowItWorks
Thevariable shoplistisashoppinglistforsomeonewhoisgoingtothemarket.In shoplist,weonlystorestringsofthenamesoftheitemstobuybutyoucanaddanykindofobjecttoalistincludingnumbersandevenotherlists.
Wehavealsousedthe for..inlooptoiteratethroughtheitemsofthelist.Bynow,youmusthaverealisedthatalistisalsoasequence.Thespecialityofsequenceswillbediscussedinalatersection.
Noticetheuseofthe endparameterinthecallto printfunctiontoindicatethatwewanttoendtheoutputwithaspaceinsteadoftheusuallinebreak.
Next,weaddanitemtothelistusingthe appendmethodofthelistobject,asalreadydiscussedbefore.Then,wecheckthattheitemhasbeenindeedaddedtothelistbyprintingthecontentsofthelistbysimplypassingthelisttothe printfunctionwhichprintsitneatly.
Then,wesortthelistbyusingthe sortmethodofthelist.Itisimportanttounderstandthatthismethodaffectsthelistitselfanddoesnotreturnamodifiedlist-thisisdifferentfromthewaystringswork.Thisiswhatwemeanbysayingthatlistsaremutableandthatstringsareimmutable.
Next,whenwefinishbuyinganiteminthemarket,wewanttoremoveitfromthelist.Weachievethisbyusingthe delstatement.Here,wementionwhichitemofthelistwewanttoremoveandthe delstatementremovesitfromthelistforus.Wespecifythatwewanttoremovethefirstitemfromthelistandhenceweuse delshoplist[0](rememberthatPythonstartscountingfrom0).
Ifyouwanttoknowallthemethodsdefinedbythelistobject,see help(list)fordetails.
Tuple
Tuplesareusedtoholdtogethermultipleobjects.Thinkofthemassimilartolists,butwithouttheextensivefunctionalitythatthelistclassgivesyou.Onemajorfeatureoftuplesisthattheyareimmutablelikestringsi.e.youcannotmodifytuples.
Tuplesaredefinedbyspecifyingitemsseparatedbycommaswithinanoptionalpairofparentheses.
Tuplesareusuallyusedincaseswhereastatementorauser-definedfunctioncansafelyassumethatthecollectionofvalues(i.e.thetupleofvaluesused)willnotchange.
Example(saveas ds_using_tuple.py):
#Iwouldrecommendalwaysusingparentheses
#toindicatestartandendoftuple
DataStructures
59
#eventhoughparenthesesareoptional.
#Explicitisbetterthanimplicit.
zoo=('python','elephant','penguin')
print('Numberofanimalsinthezoois',len(zoo))
new_zoo='monkey','camel',zoo#parenthesesnotrequiredbutareagoodidea
print('Numberofcagesinthenewzoois',len(new_zoo))
print('Allanimalsinnewzooare',new_zoo)
print('Animalsbroughtfromoldzooare',new_zoo[2])
print('Lastanimalbroughtfromoldzoois',new_zoo[2][2])
print('Numberofanimalsinthenewzoois',
len(new_zoo)-1+len(new_zoo[2]))
Output:
$pythonds_using_tuple.py
Numberofanimalsinthezoois3
Numberofcagesinthenewzoois3
Allanimalsinnewzooare('monkey','camel',('python','elephant','penguin'))
Animalsbroughtfromoldzooare('python','elephant','penguin')
Lastanimalbroughtfromoldzooispenguin
Numberofanimalsinthenewzoois5
HowItWorks
Thevariable zooreferstoatupleofitems.Weseethatthe lenfunctioncanbeusedtogetthelengthofthetuple.Thisalsoindicatesthatatupleisasequenceaswell.
Wearenowshiftingtheseanimalstoanewzoosincetheoldzooisbeingclosed.Therefore,the new_zootuplecontainssomeanimalswhicharealreadytherealongwiththeanimalsbroughtoverfromtheoldzoo.Backtoreality,notethatatuplewithinatupledoesnotloseitsidentity.
Wecanaccesstheitemsinthetuplebyspecifyingtheitem'spositionwithinapairofsquarebracketsjustlikewedidforlists.Thisiscalledtheindexingoperator.Weaccessthethirditemin new_zoobyspecifying new_zoo[2]andweaccessthethirditemwithinthethirditeminthe new_zootuplebyspecifying new_zoo[2][2].Thisisprettysimpleonceyou'veunderstoodtheidiom.
Tuplewith0or1items
Anemptytupleisconstructedbyanemptypairofparenthesessuchas myempty=().However,atuplewithasingleitemisnotsosimple.Youhavetospecifyitusingacommafollowingthefirst(andonly)itemsothatPythoncandifferentiatebetweenatupleandapairofparenthesessurroundingtheobjectinanexpressioni.e.youhavetospecify singleton=(2,)ifyoumeanyouwantatuplecontainingtheitem 2.
NoteforPerlprogrammers
Alistwithinalistdoesnotloseitsidentityi.e.listsarenotflattenedasinPerl.Thesameappliestoatuplewithinatuple,oratuplewithinalist,oralistwithinatuple,etc.AsfarasPythonisconcerned,theyarejustobjectsstoredusinganotherobject,that'sall.
Dictionary
Adictionaryislikeanaddress-bookwhereyoucanfindtheaddressorcontactdetailsofapersonbyknowingonlyhis/hernamei.e.weassociatekeys(name)withvalues(details).Notethatthekeymustbeuniquejustlikeyoucannotfindoutthecorrectinformationifyouhavetwopersonswiththeexactsamename.
Notethatyoucanuseonlyimmutableobjects(likestrings)forthekeysofadictionarybutyoucanuseeitherimmutableormutableobjectsforthevaluesofthedictionary.Thisbasicallytranslatestosaythatyoushoulduseonlysimpleobjectsforkeys.
DataStructures
60
Pairsofkeysandvaluesarespecifiedinadictionarybyusingthenotation d={key1:value1,key2:value2}.Noticethatthekey-valuepairsareseparatedbyacolonandthepairsareseparatedthemselvesbycommasandallthisisenclosedinapairofcurlybraces.
Rememberthatkey-valuepairsinadictionaryarenotorderedinanymanner.Ifyouwantaparticularorder,thenyouwillhavetosortthemyourselfbeforeusingit.
Thedictionariesthatyouwillbeusingareinstances/objectsofthe dictclass.
Example(saveas ds_using_dict.py):
#'ab'isshortfor'a'ddress'b'ook
ab={
'Swaroop':'[email protected]',
'Larry':'[email protected]',
'Matsumoto':'[email protected]',
'Spammer':'[email protected]'
}
print("Swaroop'saddressis",ab['Swaroop'])
#Deletingakey-valuepair
delab['Spammer']
print('\nThereare{}contactsintheaddress-book\n'.format(len(ab)))
forname,addressinab.items():
print('Contact{}at{}'.format(name,address))
#Addingakey-valuepair
ab['Guido']='[email protected]'
if'Guido'inab:
print("\nGuido'saddressis",ab['Guido'])
Output:
$pythonds_using_dict.py
Swaroop'[email protected]
Thereare3contactsintheaddress-book
Guido'[email protected]
HowItWorks
Wecreatethedictionary abusingthenotationalreadydiscussed.Wethenaccesskey-valuepairsbyspecifyingthekeyusingtheindexingoperatorasdiscussedinthecontextoflistsandtuples.Observethesimplesyntax.
Wecandeletekey-valuepairsusingouroldfriend-the delstatement.Wesimplyspecifythedictionaryandtheindexingoperatorforthekeytoberemovedandpassittothe delstatement.Thereisnoneedtoknowthevaluecorrespondingtothekeyforthisoperation.
Next,weaccesseachkey-valuepairofthedictionaryusingthe itemsmethodofthedictionarywhichreturnsalistoftupleswhereeachtuplecontainsapairofitems-thekeyfollowedbythevalue.Weretrievethispairandassignittothevariables nameand addresscorrespondinglyforeachpairusingthe for..inloopandthenprintthesevaluesinthefor-block.
DataStructures
61
Wecanaddnewkey-valuepairsbysimplyusingtheindexingoperatortoaccessakeyandassignthatvalue,aswehavedoneforGuidointheabovecase.
Wecancheckifakey-valuepairexistsusingthe inoperator.
Forthelistofmethodsofthe dictclass,see help(dict).
KeywordArgumentsandDictionaries
Ifyouhaveusedkeywordargumentsinyourfunctions,youhavealreadyuseddictionaries!Justthinkaboutit-thekey-valuepairisspecifiedbyyouintheparameterlistofthefunctiondefinitionandwhenyouaccessvariableswithinyourfunction,itisjustakeyaccessofadictionary(whichiscalledthesymboltableincompilerdesignterminology).
SequenceLists,tuplesandstringsareexamplesofsequences,butwhataresequencesandwhatissospecialaboutthem?
Themajorfeaturesaremembershiptests,(i.e.the inand notinexpressions)andindexingoperations,whichallowustofetchaparticulariteminthesequencedirectly.
Thethreetypesofsequencesmentionedabove-lists,tuplesandstrings,alsohaveaslicingoperationwhichallowsustoretrieveasliceofthesequencei.e.apartofthesequence.
Example(saveas ds_seq.py):
shoplist=['apple','mango','carrot','banana']
name='swaroop'
#Indexingor'Subscription'operation#
print('Item0is',shoplist[0])
print('Item1is',shoplist[1])
print('Item2is',shoplist[2])
print('Item3is',shoplist[3])
print('Item-1is',shoplist[-1])
print('Item-2is',shoplist[-2])
print('Character0is',name[0])
#Slicingonalist#
print('Item1to3is',shoplist[1:3])
print('Item2toendis',shoplist[2:])
print('Item1to-1is',shoplist[1:-1])
print('Itemstarttoendis',shoplist[:])
#Slicingonastring#
print('characters1to3is',name[1:3])
print('characters2toendis',name[2:])
print('characters1to-1is',name[1:-1])
print('charactersstarttoendis',name[:])
Output:
$pythonds_seq.py
Item0isapple
Item1ismango
Item2iscarrot
Item3isbanana
Item-1isbanana
Item-2iscarrot
Character0iss
Item1to3is['mango','carrot']
Item2toendis['carrot','banana']
Item1to-1is['mango','carrot']
DataStructures
62
Itemstarttoendis['apple','mango','carrot','banana']
characters1to3iswa
characters2toendisaroop
characters1to-1iswaroo
charactersstarttoendisswaroop
HowItWorks
First,weseehowtouseindexestogetindividualitemsofasequence.Thisisalsoreferredtoasthesubscriptionoperation.Wheneveryouspecifyanumbertoasequencewithinsquarebracketsasshownabove,Pythonwillfetchyoutheitemcorrespondingtothatpositioninthesequence.RememberthatPythonstartscountingnumbersfrom0.Hence, shoplist[0]fetchesthefirstitemand shoplist[3]fetchesthefourthiteminthe shoplistsequence.
Theindexcanalsobeanegativenumber,inwhichcase,thepositioniscalculatedfromtheendofthesequence.Therefore,shoplist[-1]referstothelastiteminthesequenceand shoplist[-2]fetchesthesecondlastiteminthesequence.
Theslicingoperationisusedbyspecifyingthenameofthesequencefollowedbyanoptionalpairofnumbersseparatedbyacolonwithinsquarebrackets.Notethatthisisverysimilartotheindexingoperationyouhavebeenusingtillnow.Rememberthenumbersareoptionalbutthecolonisn't.
Thefirstnumber(beforethecolon)intheslicingoperationreferstothepositionfromwheretheslicestartsandthesecondnumber(afterthecolon)indicateswheretheslicewillstopat.Ifthefirstnumberisnotspecified,Pythonwillstartatthebeginningofthesequence.Ifthesecondnumberisleftout,Pythonwillstopattheendofthesequence.Notethattheslicereturnedstartsatthestartpositionandwillendjustbeforetheendpositioni.e.thestartpositionisincludedbuttheendpositionisexcludedfromthesequenceslice.
Thus, shoplist[1:3]returnsasliceofthesequencestartingatposition1,includesposition2butstopsatposition3andthereforeasliceoftwoitemsisreturned.Similarly, shoplist[:]returnsacopyofthewholesequence.
Youcanalsodoslicingwithnegativepositions.Negativenumbersareusedforpositionsfromtheendofthesequence.Forexample, shoplist[:-1]willreturnasliceofthesequencewhichexcludesthelastitemofthesequencebutcontainseverythingelse.
Youcanalsoprovideathirdargumentfortheslice,whichisthestepfortheslicing(bydefault,thestepsizeis1):
>>>shoplist=['apple','mango','carrot','banana']
>>>shoplist[::1]
['apple','mango','carrot','banana']
>>>shoplist[::2]
['apple','carrot']
>>>shoplist[::3]
['apple','banana']
>>>shoplist[::-1]
['banana','carrot','mango','apple']
Noticethatwhenthestepis2,wegettheitemswithposition0,2,...Whenthestepsizeis3,wegettheitemswithposition0,3,etc.
TryvariouscombinationsofsuchslicespecificationsusingthePythoninterpreterinteractivelyi.e.thepromptsothatyoucanseetheresultsimmediately.Thegreatthingaboutsequencesisthatyoucanaccesstuples,listsandstringsallinthesameway!
Set
Setsareunorderedcollectionsofsimpleobjects.Theseareusedwhentheexistenceofanobjectinacollectionismoreimportantthantheorderorhowmanytimesitoccurs.
Usingsets,youcantestformembership,whetheritisasubsetofanotherset,findtheintersectionbetweentwosets,andsoon.
DataStructures
63
>>>bri=set(['brazil','russia','india'])
>>>'india'inbri
True
>>>'usa'inbri
False
>>>bric=bri.copy()
>>>bric.add('china')
>>>bric.issuperset(bri)
True
>>>bri.remove('russia')
>>>bri&bric#ORbri.intersection(bric)
{'brazil','india'}
HowItWorks
Ifyourememberbasicsettheorymathematicsfromschool,thenthisexampleisfairlyself-explanatory.Butifnot,youcangoogle"settheory"and"Venndiagram"tobetterunderstandouruseofsetsinPython.
ReferencesWhenyoucreateanobjectandassignittoavariable,thevariableonlyreferstotheobjectanddoesnotrepresenttheobjectitself!Thatis,thevariablenamepointstothatpartofyourcomputer'smemorywheretheobjectisstored.Thisiscalledbindingthenametotheobject.
Generally,youdon'tneedtobeworriedaboutthis,butthereisasubtleeffectduetoreferenceswhichyouneedtobeawareof:
Example(saveas ds_reference.py):
print('SimpleAssignment')
shoplist=['apple','mango','carrot','banana']
#mylistisjustanothernamepointingtothesameobject!
mylist=shoplist
#Ipurchasedthefirstitem,soIremoveitfromthelist
delshoplist[0]
print('shoplistis',shoplist)
print('mylistis',mylist)
#Noticethatbothshoplistandmylistbothprint
#thesamelistwithoutthe'apple'confirmingthat
#theypointtothesameobject
print('Copybymakingafullslice')
#Makeacopybydoingafullslice
mylist=shoplist[:]
#Removefirstitem
delmylist[0]
print('shoplistis',shoplist)
print('mylistis',mylist)
#Noticethatnowthetwolistsaredifferent
Output:
$pythonds_reference.py
SimpleAssignment
shoplistis['mango','carrot','banana']
mylistis['mango','carrot','banana']
Copybymakingafullslice
shoplistis['mango','carrot','banana']
mylistis['carrot','banana']
DataStructures
64
HowItWorks
Mostoftheexplanationisavailableinthecomments.
Rememberthatifyouwanttomakeacopyofalistorsuchkindsofsequencesorcomplexobjects(notsimpleobjectssuchasintegers),thenyouhavetousetheslicingoperationtomakeacopy.Ifyoujustassignthevariablenametoanothername,bothofthemwill''refer''tothesameobjectandthiscouldbetroubleifyouarenotcareful.
NoteforPerlprogrammers
Rememberthatanassignmentstatementforlistsdoesnotcreateacopy.Youhavetouseslicingoperationtomakeacopyofthesequence.
MoreAboutStringsWehavealreadydiscussedstringsindetailearlier.Whatmorecantherebetoknow?Well,didyouknowthatstringsarealsoobjectsandhavemethodswhichdoeverythingfromcheckingpartofastringtostrippingspaces?Infact,you'vealreadybeenusingastringmethod...the formatmethod!
Thestringsthatyouuseinprogramsareallobjectsoftheclass str.Someusefulmethodsofthisclassaredemonstratedinthenextexample.Foracompletelistofsuchmethods,see help(str).
Example(saveas ds_str_methods.py):
#Thisisastringobject
name='Swaroop'
ifname.startswith('Swa'):
print('Yes,thestringstartswith"Swa"')
if'a'inname:
print('Yes,itcontainsthestring"a"')
ifname.find('war')!=-1:
print('Yes,itcontainsthestring"war"')
delimiter='_*_'
mylist=['Brazil','Russia','India','China']
print(delimiter.join(mylist))
Output:
$pythonds_str_methods.py
Yes,thestringstartswith"Swa"
Yes,itcontainsthestring"a"
Yes,itcontainsthestring"war"
Brazil_*_Russia_*_India_*_China
HowItWorks
Here,weseealotofthestringmethodsinaction.The startswithmethodisusedtofindoutwhetherthestringstartswiththegivenstring.The inoperatorisusedtocheckifagivenstringisapartofthestring.
The findmethodisusedtolocatethepositionofthegivensubstringwithinthestring; findreturns-1ifitisunsuccessfulinfindingthesubstring.The strclassalsohasaneatmethodto jointheitemsofasequencewiththestringactingasadelimiterbetweeneachitemofthesequenceandreturnsabiggerstringgeneratedfromthis.
Summary
DataStructures
65
Wehaveexploredthevariousbuilt-indatastructuresofPythonindetail.Thesedatastructureswillbeessentialforwritingprogramsofreasonablesize.
NowthatwehavealotofthebasicsofPythoninplace,wewillnextseehowtodesignandwriteareal-worldPythonprogram.
DataStructures
66
ProblemSolvingWehaveexploredvariouspartsofthePythonlanguageandnowwewilltakealookathowallthesepartsfittogether,bydesigningandwritingaprogramwhichdoessomethinguseful.TheideaistolearnhowtowriteaPythonscriptonyourown.
TheProblem
Theproblemwewanttosolveis:
Iwantaprogramwhichcreatesabackupofallmyimportantfiles.
Although,thisisasimpleproblem,thereisnotenoughinformationforustogetstartedwiththesolution.Alittlemoreanalysisisrequired.Forexample,howdowespecifywhichfilesaretobebackedup?Howaretheystored?Wherearetheystored?
Afteranalyzingtheproblemproperly,wedesignourprogram.Wemakealistofthingsabouthowourprogramshouldwork.Inthiscase,IhavecreatedthefollowinglistonhowIwantittowork.Ifyoudothedesign,youmaynotcomeupwiththesamekindofanalysissinceeverypersonhastheirownwayofdoingthings,sothatisperfectlyokay.
Thefilesanddirectoriestobebackeduparespecifiedinalist.Thebackupmustbestoredinamainbackupdirectory.Thefilesarebackedupintoazipfile.Thenameoftheziparchiveisthecurrentdateandtime.Weusethestandard zipcommandavailablebydefaultinanystandardGNU/LinuxorUnixdistribution.Notethatyoucanuseanyarchivingcommandyouwantaslongasithasacommandlineinterface.
ForWindowsusers
Windowsuserscaninstallthe zipcommandfromtheGnuWin32projectpageandadd C:\ProgramFiles\GnuWin32\bintoyoursystem PATHenvironmentvariable,similartowhatwedidforrecognizingthepythoncommanditself.
TheSolution
Asthedesignofourprogramisnowreasonablystable,wecanwritethecodewhichisanimplementationofoursolution.
Saveas backup_ver1.py:
importos
importtime
#1.Thefilesanddirectoriestobebackedupare
#specifiedinalist.
#ExampleonWindows:
#source=['"C:\\MyDocuments"']
#ExampleonMacOSXandLinux:
source=['/Users/swa/notes']
#Noticewehavetousedoublequotesinsideastring
#fornameswithspacesinit.Wecouldhavealsoused
#arawstringbywriting[r'C:\MyDocuments'].
#2.Thebackupmustbestoredina
#mainbackupdirectory
#ExampleonWindows:
#target_dir='E:\\Backup'
#ExampleonMacOSXandLinux:
target_dir='/Users/swa/backup'
ProblemSolving
67
#Remembertochangethistowhichfolderyouwillbeusing
#3.Thefilesarebackedupintoazipfile.
#4.Thenameoftheziparchiveisthecurrentdateandtime
target=target_dir+os.sep+\
time.strftime('%Y%m%d%H%M%S')+'.zip'
#Createtargetdirectoryifitisnotpresent
ifnotos.path.exists(target_dir):
os.mkdir(target_dir)#makedirectory
#5.Weusethezipcommandtoputthefilesinaziparchive
zip_command='zip-r{0}{1}'.format(target,
''.join(source))
#Runthebackup
print('Zipcommandis:')
print(zip_command)
print('Running:')
ifos.system(zip_command)==0:
print('Successfulbackupto',target)
else:
print('BackupFAILED')
Output:
$pythonbackup_ver1.py
Zipcommandis:
zip-r/Users/swa/backup/20140328084844.zip/Users/swa/notes
Running:
adding:Users/swa/notes/(stored0%)
adding:Users/swa/notes/blah1.txt(stored0%)
adding:Users/swa/notes/blah2.txt(stored0%)
adding:Users/swa/notes/blah3.txt(stored0%)
Successfulbackupto/Users/swa/backup/20140328084844.zip
Now,weareinthetestingphasewherewetestthatourprogramworksproperly.Ifitdoesn'tbehaveasexpected,thenwehavetodebugourprogrami.e.removethebugs(errors)fromtheprogram.
Iftheaboveprogramdoesnotworkforyou,copythelineprintedafterthe Zipcommandislineintheoutput,pasteitintheshell(onGNU/LinuxandMacOSX)/ cmd(onWindows),seewhattheerrorisandtrytofixit.Alsocheckthezipcommandmanualonwhatcouldbewrong.Ifthiscommandsucceeds,thentheproblemmightbeinthePythonprogramitself,socheckifitexactlymatchestheprogramwrittenabove.
HowItWorks
Youwillnoticehowwehaveconvertedourdesignintocodeinastep-by-stepmanner.
Wemakeuseofthe osand timemodulesbyfirstimportingthem.Then,wespecifythefilesanddirectoriestobebackedupinthe sourcelist.Thetargetdirectoryiswherewestoreallthebackupfilesandthisisspecifiedinthe target_dirvariable.Thenameoftheziparchivethatwearegoingtocreateisthecurrentdateandtimewhichwegenerateusingthetime.strftime()function.Itwillalsohavethe .zipextensionandwillbestoredinthe target_dirdirectory.
Noticetheuseofthe os.sepvariable-thisgivesthedirectoryseparatoraccordingtoyouroperatingsystem,i.e.itwillbe '/'inGNU/Linux,Unix,macOS,andwillbe '\\'inWindows.Using os.sepinsteadofthesecharactersdirectlywillmakeourprogramportableandworkacrossallofthesesystems.
The time.strftime()functiontakesaspecificationsuchastheonewehaveusedintheaboveprogram.The %Yspecificationwillbereplacedbytheyearwiththecentury.The %mspecificationwillbereplacedbythemonthasadecimalnumberbetween01and 12andsoon.ThecompletelistofsuchspecificationscanbefoundinthePythonReferenceManual.
ProblemSolving
68
Wecreatethenameofthetargetzipfileusingtheadditionoperatorwhichconcatenatesthestringsi.e.itjoinsthetwostringstogetherandreturnsanewone.Then,wecreateastring zip_commandwhichcontainsthecommandthatwearegoingtoexecute.Youcancheckifthiscommandworksbyrunningitintheshell(GNU/LinuxterminalorDOSprompt).
The zipcommandthatweareusinghassomeoptionsavailable,andoneoftheseoptionsis -r.The -roptionspecifiesthatthezipcommandshouldworkrecursivelyfordirectories,i.e.itshouldincludeallthesubdirectoriesandfiles.Optionsarefollowedbythenameoftheziparchivetocreate,followedbythelistoffilesanddirectoriestobackup.Weconvertthe sourcelistintoastringusingthe joinmethodofstringswhichwehavealreadyseenhowtouse.
Then,wefinallyrunthecommandusingthe os.systemfunctionwhichrunsthecommandasifitwasrunfromthesystemi.e.intheshell-itreturns 0ifthecommandwassuccessfully,elseitreturnsanerrornumber.
Dependingontheoutcomeofthecommand,weprinttheappropriatemessagethatthebackuphasfailedorsucceeded.
That'sit,wehavecreatedascripttotakeabackupofourimportantfiles!
NotetoWindowsUsers
Insteadofdoublebackslashescapesequences,youcanalsouserawstrings.Forexample,use 'C:\\Documents'orr'C:\Documents'.However,donotuse 'C:\Documents'sinceyouendupusinganunknownescapesequence \D.
Nowthatwehaveaworkingbackupscript,wecanuseitwheneverwewanttotakeabackupofthefiles.Thisiscalledtheoperationphaseorthedeploymentphaseofthesoftware.
Theaboveprogramworksproperly,but(usually)firstprogramsdonotworkexactlyasyouexpect.Forexample,theremightbeproblemsifyouhavenotdesignedtheprogramproperlyorifyouhavemadeamistakewhentypingthecode,etc.Appropriately,youwillhavetogobacktothedesignphaseoryouwillhavetodebugyourprogram.
SecondVersion
Thefirstversionofourscriptworks.However,wecanmakesomerefinementstoitsothatitcanworkbetteronadailybasis.Thisiscalledthemaintenancephaseofthesoftware.
OneoftherefinementsIfeltwasusefulisabetterfile-namingmechanism-usingthetimeasthenameofthefilewithinadirectorywiththecurrentdateasadirectorywithinthemainbackupdirectory.Thefirstadvantageisthatyourbackupsarestoredinahierarchicalmannerandthereforeitismucheasiertomanage.Thesecondadvantageisthatthefilenamesaremuchshorter.Thethirdadvantageisthatseparatedirectorieswillhelpyoucheckifyouhavemadeabackupforeachdaysincethedirectorywouldbecreatedonlyifyouhavemadeabackupforthatday.
Saveas backup_ver2.py:
importos
importtime
#1.Thefilesanddirectoriestobebackedupare
#specifiedinalist.
#ExampleonWindows:
#source=['"C:\\MyDocuments"','C:\\Code']
#ExampleonMacOSXandLinux:
source=['/Users/swa/notes']
#Noticewehadtousedoublequotesinsidethestring
#fornameswithspacesinit.
#2.Thebackupmustbestoredina
#mainbackupdirectory
#ExampleonWindows:
#target_dir='E:\\Backup'
#ExampleonMacOSXandLinux:
target_dir='/Users/swa/backup'
#Remembertochangethistowhichfolderyouwillbeusing
ProblemSolving
69
#Createtargetdirectoryifitisnotpresent
ifnotos.path.exists(target_dir):
os.mkdir(target_dir)#makedirectory
#3.Thefilesarebackedupintoazipfile.
#4.Thecurrentdayisthenameofthesubdirectory
#inthemaindirectory.
today=target_dir+os.sep+time.strftime('%Y%m%d')
#Thecurrenttimeisthenameoftheziparchive.
now=time.strftime('%H%M%S')
#Thenameofthezipfile
target=today+os.sep+now+'.zip'
#Createthesubdirectoryifitisn'talreadythere
ifnotos.path.exists(today):
os.mkdir(today)
print('Successfullycreateddirectory',today)
#5.Weusethezipcommandtoputthefilesinaziparchive
zip_command='zip-r{0}{1}'.format(target,
''.join(source))
#Runthebackup
print('Zipcommandis:')
print(zip_command)
print('Running:')
ifos.system(zip_command)==0:
print('Successfulbackupto',target)
else:
print('BackupFAILED')
Output:
$pythonbackup_ver2.py
Successfullycreateddirectory/Users/swa/backup/20140329
Zipcommandis:
zip-r/Users/swa/backup/20140329/073201.zip/Users/swa/notes
Running:
adding:Users/swa/notes/(stored0%)
adding:Users/swa/notes/blah1.txt(stored0%)
adding:Users/swa/notes/blah2.txt(stored0%)
adding:Users/swa/notes/blah3.txt(stored0%)
Successfulbackupto/Users/swa/backup/20140329/073201.zip
HowItWorks
Mostoftheprogramremainsthesame.Thechangesarethatwecheckifthereisadirectorywiththecurrentdayasitsnameinsidethemainbackupdirectoryusingthe os.path.existsfunction.Ifitdoesn'texist,wecreateitusingthe os.mkdirfunction.
ThirdVersion
ThesecondversionworksfinewhenIdomanybackups,butwhentherearelotsofbackups,Iamfindingithardtodifferentiatewhatthebackupswerefor!Forexample,Imighthavemadesomemajorchangestoaprogramorpresentation,thenIwanttoassociatewhatthosechangesarewiththenameoftheziparchive.Thiscanbeeasilyachievedbyattachingauser-suppliedcommenttothenameoftheziparchive.
WARNING:Thefollowingprogramdoesnotwork,sodonotbealarmed,pleasefollowalongbecausethere'salessoninhere.
Saveas backup_ver3.py:
ProblemSolving
70
importos
importtime
#1.Thefilesanddirectoriestobebackedupare
#specifiedinalist.
#ExampleonWindows:
#source=['"C:\\MyDocuments"','C:\\Code']
#ExampleonMacOSXandLinux:
source=['/Users/swa/notes']
#Noticewehadtousedoublequotesinsidethestring
#fornameswithspacesinit.
#2.Thebackupmustbestoredina
#mainbackupdirectory
#ExampleonWindows:
#target_dir='E:\\Backup'
#ExampleonMacOSXandLinux:
target_dir='/Users/swa/backup'
#Remembertochangethistowhichfolderyouwillbeusing
#Createtargetdirectoryifitisnotpresent
ifnotos.path.exists(target_dir):
os.mkdir(target_dir)#makedirectory
#3.Thefilesarebackedupintoazipfile.
#4.Thecurrentdayisthenameofthesubdirectory
#inthemaindirectory.
today=target_dir+os.sep+time.strftime('%Y%m%d')
#Thecurrenttimeisthenameoftheziparchive.
now=time.strftime('%H%M%S')
#Takeacommentfromtheuserto
#createthenameofthezipfile
comment=input('Enteracomment-->')
#Checkifacommentwasentered
iflen(comment)==0:
target=today+os.sep+now+'.zip'
else:
target=today+os.sep+now+'_'+
comment.replace('','_')+'.zip'
#Createthesubdirectoryifitisn'talreadythere
ifnotos.path.exists(today):
os.mkdir(today)
print('Successfullycreateddirectory',today)
#5.Weusethezipcommandtoputthefilesinaziparchive
zip_command="zip-r{0}{1}".format(target,
''.join(source))
#Runthebackup
print('Zipcommandis:')
print(zip_command)
print('Running:')
ifos.system(zip_command)==0:
print('Successfulbackupto',target)
else:
print('BackupFAILED')
Output:
$pythonbackup_ver3.py
File"backup_ver3.py",line39
target=today+os.sep+now+'_'+
^
SyntaxError:invalidsyntax
ProblemSolving
71
HowThis(doesnot)Work
Thisprogramdoesnotwork!PythonsaysthereisasyntaxerrorwhichmeansthatthescriptdoesnotsatisfythestructurethatPythonexpectstosee.WhenweobservetheerrorgivenbyPython,italsotellsustheplacewhereitdetectedtheerroraswell.Sowestartdebuggingourprogramfromthatline.
Oncarefulobservation,weseethatthesinglelogicallinehasbeensplitintotwophysicallinesbutwehavenotspecifiedthatthesetwophysicallinesbelongtogether.Basically,Pythonhasfoundtheadditionoperator( +)withoutanyoperandinthatlogicallineandhenceitdoesn'tknowhowtocontinue.Rememberthatwecanspecifythatthelogicallinecontinuesinthenextphysicallinebytheuseofabackslashattheendofthephysicalline.So,wemakethiscorrectiontoourprogram.Thiscorrectionoftheprogramwhenwefinderrorsiscalledbugfixing.
FourthVersionSaveas backup_ver4.py:
importos
importtime
#1.Thefilesanddirectoriestobebackedupare
#specifiedinalist.
#ExampleonWindows:
#source=['"C:\\MyDocuments"','C:\\Code']
#ExampleonMacOSXandLinux:
source=['/Users/swa/notes']
#Noticewehadtousedoublequotesinsidethestring
#fornameswithspacesinit.
#2.Thebackupmustbestoredina
#mainbackupdirectory
#ExampleonWindows:
#target_dir='E:\\Backup'
#ExampleonMacOSXandLinux:
target_dir='/Users/swa/backup'
#Remembertochangethistowhichfolderyouwillbeusing
#Createtargetdirectoryifitisnotpresent
ifnotos.path.exists(target_dir):
os.mkdir(target_dir)#makedirectory
#3.Thefilesarebackedupintoazipfile.
#4.Thecurrentdayisthenameofthesubdirectory
#inthemaindirectory.
today=target_dir+os.sep+time.strftime('%Y%m%d')
#Thecurrenttimeisthenameoftheziparchive.
now=time.strftime('%H%M%S')
#Takeacommentfromtheuserto
#createthenameofthezipfile
comment=input('Enteracomment-->')
#Checkifacommentwasentered
iflen(comment)==0:
target=today+os.sep+now+'.zip'
else:
target=today+os.sep+now+'_'+\
comment.replace('','_')+'.zip'
#Createthesubdirectoryifitisn'talreadythere
ifnotos.path.exists(today):
os.mkdir(today)
print('Successfullycreateddirectory',today)
#5.Weusethezipcommandtoputthefilesinaziparchive
zip_command='zip-r{0}{1}'.format(target,
ProblemSolving
72
''.join(source))
#Runthebackup
print('Zipcommandis:')
print(zip_command)
print('Running:')
ifos.system(zip_command)==0:
print('Successfulbackupto',target)
else:
print('BackupFAILED')
Output:
$pythonbackup_ver4.py
Enteracomment-->addednewexamples
Zipcommandis:
zip-r/Users/swa/backup/20140329/074122_added_new_examples.zip/Users/swa/notes
Running:
adding:Users/swa/notes/(stored0%)
adding:Users/swa/notes/blah1.txt(stored0%)
adding:Users/swa/notes/blah2.txt(stored0%)
adding:Users/swa/notes/blah3.txt(stored0%)
Successfulbackupto/Users/swa/backup/20140329/074122_added_new_examples.zip
HowItWorks
Thisprogramnowworks!Letusgothroughtheactualenhancementsthatwehadmadeinversion3.Wetakeintheuser'scommentsusingthe inputfunctionandthencheckiftheuseractuallyenteredsomethingbyfindingoutthelengthoftheinputusingthe lenfunction.Iftheuserhasjustpressed enterwithoutenteringanything(maybeitwasjustaroutinebackupornospecialchangesweremade),thenweproceedaswehavedonebefore.
However,ifacommentwassupplied,thenthisisattachedtothenameoftheziparchivejustbeforethe .zipextension.Noticethatwearereplacingspacesinthecommentwithunderscores-thisisbecausemanagingfilenameswithoutspacesismucheasier.
MoreRefinementsThefourthversionisasatisfactorilyworkingscriptformostusers,butthereisalwaysroomforimprovement.Forexample,youcanincludeaverbositylevelforthezipcommandbyspecifyinga -voptiontomakeyourprogrambecomemoretalkativeora-qoptiontomakeitquiet.
Anotherpossibleenhancementwouldbetoallowextrafilesanddirectoriestobepassedtothescriptatthecommandline.Wecangetthesenamesfromthe sys.argvlistandwecanaddthemtoour sourcelistusingthe extendmethodprovidedbythelistclass.
Themostimportantrefinementwouldbetonotusethe os.systemwayofcreatingarchivesandinsteadusingthezipfileortarfilebuilt-inmodulestocreatethesearchives.Theyarepartofthestandardlibraryandavailablealreadyforyoutousewithoutexternaldependenciesonthezipprogramtobeavailableonyourcomputer.
However,Ihavebeenusingthe os.systemwayofcreatingabackupintheaboveexamplespurelyforpedagogicalpurposes,sothattheexampleissimpleenoughtobeunderstoodbyeverybodybutrealenoughtobeuseful.
Canyoutrywritingthefifthversionthatusesthezipfilemoduleinsteadofthe os.systemcall?
TheSoftwareDevelopmentProcessWehavenowgonethroughthevariousphasesintheprocessofwritingasoftware.Thesephasescanbesummarisedasfollows:
ProblemSolving
73
1. What(Analysis)2. How(Design)3. DoIt(Implementation)4. Test(TestingandDebugging)5. Use(OperationorDeployment)6. Maintain(Refinement)
Arecommendedwayofwritingprogramsistheprocedurewehavefollowedincreatingthebackupscript:Dotheanalysisanddesign.Startimplementingwithasimpleversion.Testanddebugit.Useittoensurethatitworksasexpected.Now,addanyfeaturesthatyouwantandcontinuetorepeattheDoIt-Test-Usecycleasmanytimesasrequired.
Remember:
Softwareisgrown,notbuilt.--BilldehÓra
Summary
WehaveseenhowtocreateourownPythonprograms/scriptsandthevariousstagesinvolvedinwritingsuchprograms.YoumayfinditusefultocreateyourownprogramjustlikewedidinthischaptersothatyoubecomecomfortablewithPythonaswellasproblem-solving.
Next,wewilldiscussobject-orientedprogramming.
ProblemSolving
74
ObjectOrientedProgrammingInalltheprogramswewrotetillnow,wehavedesignedourprogramaroundfunctionsi.e.blocksofstatementswhichmanipulatedata.Thisiscalledtheprocedure-orientedwayofprogramming.Thereisanotherwayoforganizingyourprogramwhichistocombinedataandfunctionalityandwrapitinsidesomethingcalledanobject.Thisiscalledtheobjectorientedprogrammingparadigm.Mostofthetimeyoucanuseproceduralprogramming,butwhenwritinglargeprogramsorhaveaproblemthatisbettersuitedtothismethod,youcanuseobjectorientedprogrammingtechniques.
Classesandobjectsarethetwomainaspectsofobjectorientedprogramming.Aclasscreatesanewtypewhereobjectsareinstancesoftheclass.Ananalogyisthatyoucanhavevariablesoftype intwhichtranslatestosayingthatvariablesthatstoreintegersarevariableswhichareinstances(objects)ofthe intclass.
NoteforStaticLanguageProgrammers
Notethatevenintegersaretreatedasobjects(ofthe intclass).ThisisunlikeC++andJava(beforeversion1.5)whereintegersareprimitivenativetypes.
See help(int)formoredetailsontheclass.
C#andJava1.5programmerswillfindthissimilartotheboxingandunboxingconcept.
Objectscanstoredatausingordinaryvariablesthatbelongtotheobject.Variablesthatbelongtoanobjectorclassarereferredtoasfields.Objectscanalsohavefunctionalitybyusingfunctionsthatbelongtoaclass.Suchfunctionsarecalledmethodsoftheclass.Thisterminologyisimportantbecauseithelpsustodifferentiatebetweenfunctionsandvariableswhichareindependentandthosewhichbelongtoaclassorobject.Collectively,thefieldsandmethodscanbereferredtoastheattributesofthatclass.
Fieldsareoftwotypes-theycanbelongtoeachinstance/objectoftheclassortheycanbelongtotheclassitself.Theyarecalledinstancevariablesandclassvariablesrespectively.
Aclassiscreatedusingthe classkeyword.Thefieldsandmethodsoftheclassarelistedinanindentedblock.
The self
Classmethodshaveonlyonespecificdifferencefromordinaryfunctions-theymusthaveanextrafirstnamethathastobeaddedtothebeginningoftheparameterlist,butyoudonotgiveavalueforthisparameterwhenyoucallthemethod,Pythonwillprovideit.Thisparticularvariablereferstotheobjectitself,andbyconvention,itisgiventhename self.
Although,youcangiveanynameforthisparameter,itisstronglyrecommendedthatyouusethename self-anyothernameisdefinitelyfrownedupon.Therearemanyadvantagestousingastandardname-anyreaderofyourprogramwillimmediatelyrecognizeitandevenspecializedIDEs(IntegratedDevelopmentEnvironments)canhelpyouifyouuse self.
NoteforC++/Java/C#Programmers
The selfinPythonisequivalenttothe thispointerinC++andthe thisreferenceinJavaandC#.
YoumustbewonderinghowPythongivesthevaluefor selfandwhyyoudon'tneedtogiveavalueforit.Anexamplewillmakethisclear.Sayyouhaveaclasscalled MyClassandaninstanceofthisclasscalled myobject.Whenyoucallamethodofthisobjectas myobject.method(arg1,arg2),thisisautomaticallyconvertedbyPythoninto MyClass.method(myobject,arg1,arg2)-thisisallthespecial selfisabout.
Thisalsomeansthatifyouhaveamethodwhichtakesnoarguments,thenyoustillhavetohaveoneargument-the self.
Classes
ObjectOrientedProgramming
75
Thesimplestclasspossibleisshowninthefollowingexample(saveas oop_simplestclass.py).
classPerson:
pass#Anemptyblock
p=Person()
print(p)
Output:
$pythonoop_simplestclass.py
<__main__.Personinstanceat0x10171f518>
HowItWorks
Wecreateanewclassusingthe classstatementandthenameoftheclass.Thisisfollowedbyanindentedblockofstatementswhichformthebodyoftheclass.Inthiscase,wehaveanemptyblockwhichisindicatedusingthe passstatement.
Next,wecreateanobject/instanceofthisclassusingthenameoftheclassfollowedbyapairofparentheses.(Wewilllearnmoreaboutinstantiationinthenextsection).Forourverification,weconfirmthetypeofthevariablebysimplyprintingit.Ittellsusthatwehaveaninstanceofthe Personclassinthe __main__module.
Noticethattheaddressofthecomputermemorywhereyourobjectisstoredisalsoprinted.TheaddresswillhaveadifferentvalueonyourcomputersincePythoncanstoretheobjectwhereveritfindsspace.
MethodsWehavealreadydiscussedthatclasses/objectscanhavemethodsjustlikefunctionsexceptthatwehaveanextra selfvariable.Wewillnowseeanexample(saveas oop_method.py).
classPerson:
defsay_hi(self):
print('Hello,howareyou?')
p=Person()
p.say_hi()
#Theprevious2linescanalsobewrittenas
#Person().say_hi()
Output:
$pythonoop_method.py
Hello,howareyou?
HowItWorks
Hereweseethe selfinaction.Noticethatthe say_himethodtakesnoparametersbutstillhasthe selfinthefunctiondefinition.
The __init__method
TherearemanymethodnameswhichhavespecialsignificanceinPythonclasses.Wewillseethesignificanceofthe __init__methodnow.
ObjectOrientedProgramming
76
The __init__methodisrunassoonasanobjectofaclassisinstantiated(i.e.created).Themethodisusefultodoanyinitialization(i.e.passinginitialvaluestoyourobject)youwanttodowithyourobject.Noticethedoubleunderscoresbothatthebeginningandattheendofthename.
Example(saveas oop_init.py):
classPerson:
def__init__(self,name):
self.name=name
defsay_hi(self):
print('Hello,mynameis',self.name)
p=Person('Swaroop')
p.say_hi()
#Theprevious2linescanalsobewrittenas
#Person('Swaroop').say_hi()
Output:
$pythonoop_init.py
Hello,mynameisSwaroop
HowItWorks
Here,wedefinethe __init__methodastakingaparameter name(alongwiththeusual self).Here,wejustcreateanewfieldalsocalled name.Noticethesearetwodifferentvariableseventhoughtheyarebothcalled'name'.Thereisnoproblembecausethedottednotation self.namemeansthatthereissomethingcalled"name"thatispartoftheobjectcalled"self"andtheother nameisalocalvariable.Sinceweexplicitlyindicatewhichnamewearereferringto,thereisnoconfusion.
Whencreatingnewinstance p,oftheclass Person,wedosobyusingtheclassname,followedbytheargumentsintheparentheses:p=Person('Swaroop').
Wedonotexplicitlycallthe __init__method.Thisisthespecialsignificanceofthismethod.
Now,weareabletousethe self.namefieldinourmethodswhichisdemonstratedinthe say_himethod.
ClassAndObjectVariables
Wehavealreadydiscussedthefunctionalitypartofclassesandobjects(i.e.methods),nowletuslearnaboutthedatapart.Thedatapart,i.e.fields,arenothingbutordinaryvariablesthatareboundtothenamespacesoftheclassesandobjects.Thismeansthatthesenamesarevalidwithinthecontextoftheseclassesandobjectsonly.That'swhytheyarecallednamespaces.
Therearetwotypesoffields-classvariablesandobjectvariableswhichareclassifieddependingonwhethertheclassortheobjectownsthevariablesrespectively.
Classvariablesareshared-theycanbeaccessedbyallinstancesofthatclass.Thereisonlyonecopyoftheclassvariableandwhenanyoneobjectmakesachangetoaclassvariable,thatchangewillbeseenbyalltheotherinstances.
Objectvariablesareownedbyeachindividualobject/instanceoftheclass.Inthiscase,eachobjecthasitsowncopyofthefieldi.e.theyarenotsharedandarenotrelatedinanywaytothefieldbythesamenameinadifferentinstance.Anexamplewillmakethiseasytounderstand(saveas oop_objvar.py):
classRobot:
"""Representsarobot,withaname."""
#Aclassvariable,countingthenumberofrobots
population=0
ObjectOrientedProgramming
77
def__init__(self,name):
"""Initializesthedata."""
self.name=name
print("(Initializing{})".format(self.name))
#Whenthispersoniscreated,therobot
#addstothepopulation
Robot.population+=1
defdie(self):
"""Iamdying."""
print("{}isbeingdestroyed!".format(self.name))
Robot.population-=1
ifRobot.population==0:
print("{}wasthelastone.".format(self.name))
else:
print("Therearestill{:d}robotsworking.".format(
Robot.population))
defsay_hi(self):
"""Greetingbytherobot.
Yeah,theycandothat."""
print("Greetings,mymasterscallme{}.".format(self.name))
@classmethod
defhow_many(cls):
"""Printsthecurrentpopulation."""
print("Wehave{:d}robots.".format(cls.population))
droid1=Robot("R2-D2")
droid1.say_hi()
Robot.how_many()
droid2=Robot("C-3PO")
droid2.say_hi()
Robot.how_many()
print("\nRobotscandosomeworkhere.\n")
print("Robotshavefinishedtheirwork.Solet'sdestroythem.")
droid1.die()
droid2.die()
Robot.how_many()
Output:
$pythonoop_objvar.py
(InitializingR2-D2)
Greetings,mymasterscallmeR2-D2.
Wehave1robots.
(InitializingC-3PO)
Greetings,mymasterscallmeC-3PO.
Wehave2robots.
Robotscandosomeworkhere.
Robotshavefinishedtheirwork.Solet'sdestroythem.
R2-D2isbeingdestroyed!
Therearestill1robotsworking.
C-3POisbeingdestroyed!
C-3POwasthelastone.
ObjectOrientedProgramming
78
Wehave0robots.
HowItWorks
Thisisalongexamplebuthelpsdemonstratethenatureofclassandobjectvariables.Here, populationbelongstothe Robotclassandhenceisaclassvariable.The namevariablebelongstotheobject(itisassignedusing self)andhenceisanobjectvariable.
Thus,werefertothe populationclassvariableas Robot.populationandnotas self.population.Werefertotheobjectvariable nameusing self.namenotationinthemethodsofthatobject.Rememberthissimpledifferencebetweenclassandobjectvariables.Alsonotethatanobjectvariablewiththesamenameasaclassvariablewillhidetheclassvariable!
Insteadof Robot.population,wecouldhavealsoused self.__class__.populationbecauseeveryobjectreferstoitsclassviathe self.__class__attribute.
The how_manyisactuallyamethodthatbelongstotheclassandnottotheobject.Thismeanswecandefineitaseitheraclassmethodora staticmethoddependingonwhetherweneedtoknowwhichclasswearepartof.Sincewerefertoaclassvariable,let'suse classmethod.
Wehavemarkedthe how_manymethodasaclassmethodusingadecorator.
Decoratorscanbeimaginedtobeashortcuttocallingawrapperfunction(i.e.afunctionthat"wraps"aroundanotherfunctionsothatitcandosomethingbeforeoraftertheinnerfunction),soapplyingthe @classmethoddecoratoristhesameascalling:
how_many=classmethod(how_many)
Observethatthe __init__methodisusedtoinitializethe Robotinstancewithaname.Inthismethod,weincreasethepopulationcountby1sincewehaveonemorerobotbeingadded.Alsoobservethatthevaluesof self.nameisspecifictoeachobjectwhichindicatesthenatureofobjectvariables.
Remember,thatyoumustrefertothevariablesandmethodsofthesameobjectusingthe selfonly.Thisiscalledanattributereference.
Inthisprogram,wealsoseetheuseofdocstringsforclassesaswellasmethods.Wecanaccesstheclassdocstringatruntimeusing Robot.__doc__andthemethoddocstringas Robot.say_hi.__doc__
Inthe diemethod,wesimplydecreasethe Robot.populationcountby1.
Allclassmembersarepublic.Oneexception:Ifyouusedatamemberswithnamesusingthedoubleunderscoreprefixsuchas__privatevar,Pythonusesname-manglingtoeffectivelymakeitaprivatevariable.
Thus,theconventionfollowedisthatanyvariablethatistobeusedonlywithintheclassorobjectshouldbeginwithanunderscoreandallothernamesarepublicandcanbeusedbyotherclasses/objects.RememberthatthisisonlyaconventionandisnotenforcedbyPython(exceptforthedoubleunderscoreprefix).
NoteforC++/Java/C#Programmers
Allclassmembers(includingthedatamembers)arepublicandallthemethodsarevirtualinPython.
Inheritance
Oneofthemajorbenefitsofobjectorientedprogrammingisreuseofcodeandoneofthewaysthisisachievedisthroughtheinheritancemechanism.Inheritancecanbebestimaginedasimplementingatypeandsubtyperelationshipbetweenclasses.
Supposeyouwanttowriteaprogramwhichhastokeeptrackoftheteachersandstudentsinacollege.Theyhavesomecommoncharacteristicssuchasname,ageandaddress.Theyalsohavespecificcharacteristicssuchassalary,coursesandleavesforteachersand,marksandfeesforstudents.
ObjectOrientedProgramming
79
Youcancreatetwoindependentclassesforeachtypeandprocessthembutaddinganewcommoncharacteristicwouldmeanaddingtobothoftheseindependentclasses.Thisquicklybecomesunwieldy.
Abetterwaywouldbetocreateacommonclasscalled SchoolMemberandthenhavetheteacherandstudentclassesinheritfromthisclass,i.e.theywillbecomesub-typesofthistype(class)andthenwecanaddspecificcharacteristicstothesesub-types.
Therearemanyadvantagestothisapproach.Ifweadd/changeanyfunctionalityin SchoolMember,thisisautomaticallyreflectedinthesubtypesaswell.Forexample,youcanaddanewIDcardfieldforbothteachersandstudentsbysimplyaddingittotheSchoolMemberclass.However,changesinthesubtypesdonotaffectothersubtypes.Anotheradvantageisthatyoucanrefertoateacherorstudentobjectasa SchoolMemberobjectwhichcouldbeusefulinsomesituationssuchascountingofthenumberofschoolmembers.Thisiscalledpolymorphismwhereasub-typecanbesubstitutedinanysituationwhereaparenttypeisexpected,i.e.theobjectcanbetreatedasaninstanceoftheparentclass.
Alsoobservethatwereusethecodeoftheparentclassandwedonotneedtorepeatitinthedifferentclassesaswewouldhavehadtoincasewehadusedindependentclasses.
The SchoolMemberclassinthissituationisknownasthebaseclassorthesuperclass.The Teacherand Studentclassesarecalledthederivedclassesorsubclasses.
Wewillnowseethisexampleasaprogram(saveas oop_subclass.py):
classSchoolMember:
'''Representsanyschoolmember.'''
def__init__(self,name,age):
self.name=name
self.age=age
print('(InitializedSchoolMember:{})'.format(self.name))
deftell(self):
'''Tellmydetails.'''
print('Name:"{}"Age:"{}"'.format(self.name,self.age),end="")
classTeacher(SchoolMember):
'''Representsateacher.'''
def__init__(self,name,age,salary):
SchoolMember.__init__(self,name,age)
self.salary=salary
print('(InitializedTeacher:{})'.format(self.name))
deftell(self):
SchoolMember.tell(self)
print('Salary:"{:d}"'.format(self.salary))
classStudent(SchoolMember):
'''Representsastudent.'''
def__init__(self,name,age,marks):
SchoolMember.__init__(self,name,age)
self.marks=marks
print('(InitializedStudent:{})'.format(self.name))
deftell(self):
SchoolMember.tell(self)
print('Marks:"{:d}"'.format(self.marks))
t=Teacher('Mrs.Shrividya',40,30000)
s=Student('Swaroop',25,75)
#printsablankline
print()
members=[t,s]
formemberinmembers:
#WorksforbothTeachersandStudents
ObjectOrientedProgramming
80
member.tell()
Output:
$pythonoop_subclass.py
(InitializedSchoolMember:Mrs.Shrividya)
(InitializedTeacher:Mrs.Shrividya)
(InitializedSchoolMember:Swaroop)
(InitializedStudent:Swaroop)
Name:"Mrs.Shrividya"Age:"40"Salary:"30000"
Name:"Swaroop"Age:"25"Marks:"75"
HowItWorks
Touseinheritance,wespecifythebaseclassnamesinatuplefollowingtheclassnameintheclassdefinition(forexample, classTeacher(SchoolMember)).Next,weobservethatthe __init__methodofthebaseclassisexplicitlycalledusingthe selfvariablesothatwecaninitializethebaseclasspartofaninstanceinthesubclass.Thisisveryimportanttoremember-Sincewearedefininga __init__methodin Teacherand Studentsubclasses,Pythondoesnotautomaticallycalltheconstructorofthebaseclass SchoolMember,youhavetoexplicitlycallityourself.
Incontrast,ifwehavenotdefinedan __init__methodinasubclass,Pythonwillcalltheconstructorofthebaseclassautomatically.
Whilewecouldtreatinstancesof Teacheror Studentaswewouldaninstanceof SchoolMemberandaccessthe tellmethodof SchoolMemberbysimplytyping Teacher.tellor Student.tell,weinsteaddefineanother tellmethodineachsubclass(usingthe tellmethodof SchoolMemberforpartofit)totailoritforthatsubclass.Becausewehavedonethis,whenwewrite Teacher.tellPythonusesthe tellmethodforthatsubclassvsthesuperclass.However,ifwedidnothavea tellmethodinthesubclass,Pythonwouldusethe tellmethodinthesuperclass.Pythonalwaysstartslookingformethodsintheactualsubclasstypefirst,andifitdoesn�tfindanything,itstartslookingatthemethodsinthesubclass�sbaseclasses,onebyoneintheordertheyarespecifiedinthetuple(hereweonlyhave1baseclass,butyoucanhavemultiplebaseclasses)intheclassdefinition.
Anoteonterminology-ifmorethanoneclassislistedintheinheritancetuple,thenitiscalledmultipleinheritance.
The endparameterisusedinthe printfunctioninthesuperclass's tell()methodtoprintalineandallowthenextprinttocontinueonthesameline.Thisisatricktomake printnotprinta \n(newline)symbolattheendoftheprinting.
Summary
Wehavenowexploredthevariousaspectsofclassesandobjectsaswellasthevariousterminologiesassociatedwithit.Wehavealsoseenthebenefitsandpitfallsofobject-orientedprogramming.Pythonishighlyobject-orientedandunderstandingtheseconceptscarefullywillhelpyoualotinthelongrun.
Next,wewilllearnhowtodealwithinput/outputandhowtoaccessfilesinPython.
ObjectOrientedProgramming
81
InputandOutputTherewillbesituationswhereyourprogramhastointeractwiththeuser.Forexample,youwouldwanttotakeinputfromtheuserandthenprintsomeresultsback.Wecanachievethisusingthe input()functionand printfunctionrespectively.
Foroutput,wecanalsousethevariousmethodsofthe str(string)class.Forexample,youcanusethe rjustmethodtogetastringwhichisrightjustifiedtoaspecifiedwidth.See help(str)formoredetails.
Anothercommontypeofinput/outputisdealingwithfiles.Theabilitytocreate,readandwritefilesisessentialtomanyprogramsandwewillexplorethisaspectinthischapter.
InputfromuserSavethisprogramas io_input.py:
defreverse(text):
returntext[::-1]
defis_palindrome(text):
returntext==reverse(text)
something=input("Entertext:")
ifis_palindrome(something):
print("Yes,itisapalindrome")
else:
print("No,itisnotapalindrome")
Output:
$python3io_input.py
Entertext:sir
No,itisnotapalindrome
$python3io_input.py
Entertext:madam
Yes,itisapalindrome
$python3io_input.py
Entertext:racecar
Yes,itisapalindrome
HowItWorks
Weusetheslicingfeaturetoreversethetext.We'vealreadyseenhowwecanmakeslicesfromsequencesusingthe seq[a:b]codestartingfromposition atoposition b.Wecanalsoprovideathirdargumentthatdeterminesthestepbywhichtheslicingisdone.Thedefaultstepis 1becauseofwhichitreturnsacontinuouspartofthetext.Givinganegativestep,i.e., -1willreturnthetextinreverse.
The input()functiontakesastringasargumentanddisplaysittotheuser.Thenitwaitsfortheusertotypesomethingandpressthereturnkey.Oncetheuserhasenteredandpressedthereturnkey,the input()functionwillthenreturnthattexttheuserhasentered.
Wetakethattextandreverseit.Iftheoriginaltextandreversedtextareequal,thenthetextisapalindrome.
InputandOutput
82
Homeworkexercise
Checkingwhetheratextisapalindromeshouldalsoignorepunctuation,spacesandcase.Forexample,"Risetovote,sir."isalsoapalindromebutourcurrentprogramdoesn'tsayitis.Canyouimprovetheaboveprogramtorecognizethispalindrome?
Ifyouneedahint,theideaisthat...
FilesYoucanopenandusefilesforreadingorwritingbycreatinganobjectofthe fileclassandusingits read, readlineorwritemethodsappropriatelytoreadfromorwritetothefile.Theabilitytoreadorwritetothefiledependsonthemodeyouhavespecifiedforthefileopening.Thenfinally,whenyouarefinishedwiththefile,youcallthe closemethodtotellPythonthatwearedoneusingthefile.
Example(saveas io_using_file.py):
poem='''\
Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
'''
#Openfor'w'riting
f=open('poem.txt','w')
#Writetexttofile
f.write(poem)
#Closethefile
f.close()
#Ifnomodeisspecified,
#'r'eadmodeisassumedbydefault
f=open('poem.txt')
whileTrue:
line=f.readline()
#ZerolengthindicatesEOF
iflen(line)==0:
break
#The`line`alreadyhasanewline
#attheendofeachline
#sinceitisreadingfromafile.
print(line,end='')
#closethefile
f.close()
Output:
$python3io_using_file.py
Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
HowItWorks
Notethatwecancreateanewfileobjectsimplybyusingthe openmethod.Weopen(orcreateitifitdoesn'talreadyexist)thisfilebyusingthebuilt-in openfunctionandspecifyingthenameofthefileandthemodeinwhichwewanttoopenthefile.Themodecanbeareadmode( 'r'),writemode( 'w')orappendmode( 'a').Wecanalsospecifywhetherwearereading,
1
InputandOutput
83
writing,orappendingintextmode( 't')orbinarymode( 'b').Thereareactuallymanymoremodesavailableandhelp(open)willgiveyoumoredetailsaboutthem.Bydefault, open()considersthefiletobea't'extfileandopensitin'r'eadmode.
Inourexample,wefirstopen/createthefileinwritetextmodeandusethe writemethodofthefileobjecttowriteourstringvariable poemtothefileandthenwefinally closethefile.
Next,weopenthesamefileagainforreading.Wedon'tneedtospecifyamodebecause'readtextfile'isthedefaultmode.Wereadineachlineofthefileusingthe readlinemethodinaloop.Thismethodreturnsacompletelineincludingthenewlinecharacterattheendoftheline.Whenanemptystringisreturned,itmeansthatwehavereachedtheendofthefileandwe'break'outoftheloop.
Intheend,wefinally closethefile.
Wecanseefromour readlineoutputthatthisprogramhasindeedwrittentoandreadfromournew poem.txtfile.
PicklePythonprovidesastandardmodulecalled picklewhichyoucanusetostoreanyplainPythonobjectinafileandthengetitbacklater.Thisiscalledstoringtheobjectpersistently.
Example(saveas io_pickle.py):
importpickle
#Thenameofthefilewherewewillstoretheobject
shoplistfile='shoplist.data'
#Thelistofthingstobuy
shoplist=['apple','mango','carrot']
#Writetothefile
f=open(shoplistfile,'wb')
#Dumptheobjecttoafile
pickle.dump(shoplist,f)
f.close()
#Destroytheshoplistvariable
delshoplist
#Readbackfromthestorage
f=open(shoplistfile,'rb')
#Loadtheobjectfromthefile
storedlist=pickle.load(f)
print(storedlist)
f.close()
Output:
$pythonio_pickle.py
['apple','mango','carrot']
HowItWorks
Tostoreanobjectinafile,wehavetofirst openthefileinwritebinarymodeandthencallthe dumpfunctionofthe picklemodule.Thisprocessiscalledpickling.
Next,weretrievetheobjectusingthe loadfunctionofthe picklemodulewhichreturnstheobject.Thisprocessiscalledunpickling.
InputandOutput
84
Unicode
Sofar,whenwehavebeenwritingandusingstrings,orreadingandwritingtoafile,wehaveusedsimpleEnglishcharactersonly.BothEnglishandnon-EnglishcharacterscanberepresentedinUnicode(pleaseseethearticlesattheendofthissectionformoreinfo),andPython3bydefaultstoresstringvariables(thinkofallthattextwewroteusingsingleordoubleortriplequotes)inUnicode.
NOTE:IfyouareusingPython2,andwewanttobeabletoreadandwriteothernon-Englishlanguages,weneedtousethe unicodetype,anditallstartswiththecharacter u,e.g. u"helloworld"
>>>"helloworld"
'helloworld'
>>>type("helloworld")
<class'str'>
>>>u"helloworld"
'helloworld'
>>>type(u"helloworld")
<class'str'>
WhendataissentovertheInternet,weneedtosenditinbytes...somethingyourcomputereasilyunderstands.TherulesfortranslatingUnicode(whichiswhatPythonuseswhenitstoresastring)tobytesiscalledencoding.ApopularencodingtouseisUTF-8.WecanreadandwriteinUTF-8byusingasimplekeywordargumentinour openfunction.
#encoding=utf-8
importio
f=io.open("abc.txt","wt",encoding="utf-8")
f.write(u"Imaginenon-Englishlanguagehere")
f.close()
text=io.open("abc.txt",encoding="utf-8").read()
print(text)
HowItWorks
Weuse io.openandthenusethe encodingargumentinthefirstopenstatementtoencodethemessage,andthenagaininthesecondopenstatementwhendecodingthemessage.Notethatweshouldonlyuseencodingintheopenstatementwhenintextmode.
WheneverwewriteaprogramthatusesUnicodeliterals(byputtinga ubeforethestring)likewehaveusedabove,wehavetomakesurethatPythonitselfistoldthatourprogramusesUTF-8,andwehavetoput #encoding=utf-8commentatthetopofourprogram.
Youshouldlearnmoreaboutthistopicbyreading:
"TheAbsoluteMinimumEverySoftwareDeveloperAbsolutely,PositivelyMustKnowAboutUnicodeandCharacterSets"PythonUnicodeHowtoPragmaticUnicodetalkbyNatBatchelder
SummaryWehavediscussedvarioustypesofinput/output,aboutfilehandling,aboutthepicklemoduleandaboutUnicode.
Next,wewillexploretheconceptofexceptions.
1
InputandOutput
85
.Useatuple(youcanfindalistofallpunctuationmarkshere)toholdalltheforbiddencharacters,thenusethemembershiptesttodeterminewhetheracharactershouldberemovedornot,i.e.forbidden=( !, ?, .,...).↩
1
InputandOutput
86
ExceptionsExceptionsoccurwhenexceptionalsituationsoccurinyourprogram.Forexample,whatifyouaregoingtoreadafileandthefiledoesnotexist?Orwhatifyouaccidentallydeleteditwhentheprogramwasrunning?Suchsituationsarehandledusingexceptions.
Similarly,whatifyourprogramhadsomeinvalidstatements?ThisishandledbyPythonwhichraisesitshandsandtellsyouthereisanerror.
Errors
Considerasimple printfunctioncall.Whatifwemisspelt printas Print?Notethecapitalization.Inthiscase,Pythonraisesasyntaxerror.
>>>Print("HelloWorld")
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
NameError:name'Print'isnotdefined
>>>print("HelloWorld")
HelloWorld
Observethata NameErrorisraisedandalsothelocationwheretheerrorwasdetectedisprinted.Thisiswhatanerrorhandlerforthiserrordoes.
Exceptions
Wewilltrytoreadinputfromtheuser.Enterthefirstlinebelowandhitthe Enterkey.Whenyourcomputerpromptsyouforinput,insteadpress [ctrl-d]onaMacor [ctrl-z]withWindowsandseewhathappens.(Ifyou'reusingWindowsandneitheroptionworks,youcantry [ctrl-c]intheCommandPrompttogenerateaKeyboardInterrupterrorinstead).
>>>s=input('Entersomething-->')
Entersomething-->Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
EOFError
Pythonraisesanerrorcalled EOFErrorwhichbasicallymeansitfoundanendoffilesymbol(whichisrepresentedby ctrl-d)whenitdidnotexpecttoseeit.
HandlingExceptionsWecanhandleexceptionsusingthe try..exceptstatement.Webasicallyputourusualstatementswithinthetry-blockandputallourerrorhandlersintheexcept-block.
Example(saveas exceptions_handle.py):
try:
text=input('Entersomething-->')
exceptEOFError:
print('WhydidyoudoanEOFonme?')
exceptKeyboardInterrupt:
print('Youcancelledtheoperation.')
Exceptions
87
else:
print('Youentered{}'.format(text))
Output:
#Pressctrl+d
$pythonexceptions_handle.py
Entersomething-->WhydidyoudoanEOFonme?
#Pressctrl+c
$pythonexceptions_handle.py
Entersomething-->^CYoucancelledtheoperation.
$pythonexceptions_handle.py
Entersomething-->Noexceptions
YouenteredNoexceptions
HowItWorks
Weputallthestatementsthatmightraiseexceptions/errorsinsidethe tryblockandthenputhandlersfortheappropriateerrors/exceptionsinthe exceptclause/block.The exceptclausecanhandleasinglespecifiederrororexception,oraparenthesizedlistoferrors/exceptions.Ifnonamesoferrorsorexceptionsaresupplied,itwillhandleallerrorsandexceptions.
Notethattherehastobeatleastone exceptclauseassociatedwithevery tryclause.Otherwise,what'sthepointofhavingatryblock?
Ifanyerrororexceptionisnothandled,thenthedefaultPythonhandleriscalledwhichjuststopstheexecutionoftheprogramandprintsanerrormessage.Wehavealreadyseenthisinactionabove.
Youcanalsohavean elseclauseassociatedwitha try..exceptblock.The elseclauseisexecutedifnoexceptionoccurs.
Inthenextexample,wewillalsoseehowtogettheexceptionobjectsothatwecanretrieveadditionalinformation.
RaisingExceptions
Youcanraiseexceptionsusingthe raisestatementbyprovidingthenameoftheerror/exceptionandtheexceptionobjectthatistobethrown.
Theerrororexceptionthatyoucanraiseshouldbeaclasswhichdirectlyorindirectlymustbeaderivedclassofthe Exceptionclass.
Example(saveas exceptions_raise.py):
classShortInputException(Exception):
'''Auser-definedexceptionclass.'''
def__init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast
try:
text=input('Entersomething-->')
iflen(text)<3:
raiseShortInputException(len(text),3)
#Otherworkcancontinueasusualhere
exceptEOFError:
print('WhydidyoudoanEOFonme?')
exceptShortInputExceptionasex:
print(('ShortInputException:Theinputwas'+
'{0}long,expectedatleast{1}')
.format(ex.length,ex.atleast))
Exceptions
88
else:
print('Noexceptionwasraised.')
Output:
$pythonexceptions_raise.py
Entersomething-->a
ShortInputException:Theinputwas1long,expectedatleast3
$pythonexceptions_raise.py
Entersomething-->abc
Noexceptionwasraised.
HowItWorks
Here,wearecreatingourownexceptiontype.Thisnewexceptiontypeiscalled ShortInputException.Ithastwofields-lengthwhichisthelengthofthegiveninput,and atleastwhichistheminimumlengththattheprogramwasexpecting.
Inthe exceptclause,wementiontheclassoferrorwhichwillbestored asthevariablenametoholdthecorrespondingerror/exceptionobject.Thisisanalogoustoparametersandargumentsinafunctioncall.Withinthisparticular exceptclause,weusethe lengthand atleastfieldsoftheexceptionobjecttoprintanappropriatemessagetotheuser.
Try...FinallySupposeyouarereadingafileinyourprogram.Howdoyouensurethatthefileobjectisclosedproperlywhetherornotanexceptionwasraised?Thiscanbedoneusingthe finallyblock.
Savethisprogramas exceptions_finally.py:
importsys
importtime
f=None
try:
f=open("poem.txt")
#Ourusualfile-readingidiom
whileTrue:
line=f.readline()
iflen(line)==0:
break
print(line,end='')
sys.stdout.flush()
print("Pressctrl+cnow")
#Tomakesureitrunsforawhile
time.sleep(2)
exceptIOError:
print("Couldnotfindfilepoem.txt")
exceptKeyboardInterrupt:
print("!!Youcancelledthereadingfromthefile.")
finally:
iff:
f.close()
print("(Cleaningup:Closedthefile)")
Output:
$pythonexceptions_finally.py
Programmingisfun
Pressctrl+cnow
^C!!Youcancelledthereadingfromthefile.
Exceptions
89
(Cleaningup:Closedthefile)
HowItWorks
Wedotheusualfile-readingstuff,butwehavearbitrarilyintroducedsleepingfor2secondsafterprintingeachlineusingthetime.sleepfunctionsothattheprogramrunsslowly(Pythonisveryfastbynature).Whentheprogramisstillrunning,pressctrl+ctointerrupt/canceltheprogram.
Observethatthe KeyboardInterruptexceptionisthrownandtheprogramquits.However,beforetheprogramexits,thefinallyclauseisexecutedandthefileobjectisalwaysclosed.
Noticethatavariableassignedavalueof0or Noneoravariablewhichisanemptysequenceorcollectionisconsidered FalsebyPython.Thisiswhywecanuse iff:inthecodeabove.
Alsonotethatweuse sys.stdout.flush()after printsothatitprintstothescreenimmediately.
Thewithstatement
Acquiringaresourceinthe tryblockandsubsequentlyreleasingtheresourceinthe finallyblockisacommonpattern.Hence,thereisalsoa withstatementthatenablesthistobedoneinacleanmanner:
Saveas exceptions_using_with.py:
withopen("poem.txt")asf:
forlineinf:
print(line,end='')
HowItWorks
Theoutputshouldbesameasthepreviousexample.Thedifferencehereisthatweareusingthe openfunctionwiththe withstatement-weleavetheclosingofthefiletobedoneautomaticallyby withopen.
Whathappensbehindthescenesisthatthereisaprotocolusedbythe withstatement.Itfetchestheobjectreturnedbytheopenstatement,let'scallit"thefile"inthiscase.
Italwayscallsthe thefile.__enter__functionbeforestartingtheblockofcodeunderitandalwayscalls thefile.__exit__afterfinishingtheblockofcode.
Sothecodethatwewouldhavewrittenina finallyblockshouldbetakencareofautomaticallybythe __exit__method.Thisiswhathelpsustoavoidhavingtouseexplicit try..finallystatementsrepeatedly.
Morediscussiononthistopicisbeyondscopeofthisbook,sopleasereferPEP343foracomprehensiveexplanation.
Summary
Wehavediscussedtheusageofthe try..exceptand try..finallystatements.Wehaveseenhowtocreateourownexceptiontypesandhowtoraiseexceptionsaswell.
Next,wewillexplorethePythonStandardLibrary.
Exceptions
90
StandardLibraryThePythonStandardLibrarycontainsahugenumberofusefulmodulesandispartofeverystandardPythoninstallation.ItisimportanttobecomefamiliarwiththePythonStandardLibrarysincemanyproblemscanbesolvedquicklyifyouarefamiliarwiththerangeofthingsthattheselibrariescando.
Wewillexploresomeofthecommonlyusedmodulesinthislibrary.YoucanfindcompletedetailsforallofthemodulesinthePythonStandardLibraryinthe'LibraryReference'sectionofthedocumentationthatcomeswithyourPythoninstallation.
Letusexploreafewusefulmodules.
CAUTION:Ifyoufindthetopicsinthischaptertooadvanced,youmayskipthischapter.However,IhighlyrecommendcomingbacktothischapterwhenyouaremorecomfortablewithprogrammingusingPython.
sysmodule
The sysmodulecontainssystem-specificfunctionality.Wehavealreadyseenthatthe sys.argvlistcontainsthecommand-linearguments.
SupposewewanttochecktheversionofthePythonsoftwarebeingused,the sysmodulegivesusthatinformation.
>>>importsys
>>>sys.version_info
sys.version_info(major=3,minor=6,micro=0,releaselevel='final',serial=0)
>>>sys.version_info.major==3
True
HowItWorks
The sysmodulehasa version_infotuplethatgivesustheversioninformation.Thefirstentryisthemajorversion.Wecanpulloutthisinformationtouseit.
loggingmoduleWhatifyouwantedtohavesomedebuggingmessagesorimportantmessagestobestoredsomewheresothatyoucancheckwhetheryourprogramhasbeenrunningasyouwouldexpectit?Howdoyou"storesomewhere"thesemessages?Thiscanbeachievedusingthe loggingmodule.
Saveas stdlib_logging.py:
importos
importplatform
importlogging
ifplatform.platform().startswith('Windows'):
logging_file=os.path.join(os.getenv('HOMEDRIVE'),
os.getenv('HOMEPATH'),
'test.log')
else:
logging_file=os.path.join(os.getenv('HOME'),
'test.log')
print("Loggingto",logging_file)
logging.basicConfig(
StandardLibrary
91
level=logging.DEBUG,
format='%(asctime)s:%(levelname)s:%(message)s',
filename=logging_file,
filemode='w',
)
logging.debug("Startoftheprogram")
logging.info("Doingsomething")
logging.warning("Dyingnow")
Output:
$pythonstdlib_logging.py
Loggingto/Users/swa/test.log
$cat/Users/swa/test.log
2014-03-2909:27:36,660:DEBUG:Startoftheprogram
2014-03-2909:27:36,660:INFO:Doingsomething
2014-03-2909:27:36,660:WARNING:Dyingnow
The catcommandisusedinthecommandlinetoreadthe'test.log'file.Ifthe catcommandisnotavailable,youcanopenthetest.logfileinatexteditorinstead.
HowItWorks
Weusethreemodulesfromthestandardlibrary-the osmoduleforinteractingwiththeoperatingsystem,the platformmoduleforinformationabouttheplatformi.e.theoperatingsystemandthe loggingmoduletologinformation.
First,wecheckwhichoperatingsystemweareusingbycheckingthestringreturnedby platform.platform()(formoreinformation,see importplatform;help(platform)).IfitisWindows,wefigureoutthehomedrive,thehomefolderandthefilenamewherewewanttostoretheinformation.Puttingthesethreepartstogether,wegetthefulllocationofthefile.Forotherplatforms,weneedtoknowjustthehomefolderoftheuserandwegetthefulllocationofthefile.
Weusethe os.path.join()functiontoputthesethreepartsofthelocationtogether.Thereasontouseaspecialfunctionratherthanjustaddingthestringstogetherisbecausethisfunctionwillensurethefulllocationmatchestheformatexpectedbytheoperatingsystem.Note:the join()methodweuseherethat'spartofthe osmoduleisdifferentfromthestringmethodjoin()thatwe'veusedelsewhereinthisbook.
Weconfigurethe loggingmoduletowriteallthemessagesinaparticularformattothefilewehavespecified.
Finally,wecanputmessagesthatareeithermeantfordebugging,information,warningorevencriticalmessages.Oncetheprogramhasrun,wecancheckthisfileandwewillknowwhathappenedintheprogram,eventhoughnoinformationwasdisplayedtotheuserrunningtheprogram.
ModuleoftheWeekSeriesThereismuchmoretobeexploredinthestandardlibrarysuchasdebugging,handlingcommandlineoptions,regularexpressionsandsoon.
ThebestwaytofurtherexplorethestandardlibraryistoreadDougHellmann'sexcellentPythonModuleoftheWeekseries(alsoavailableasabook)andreadingthePythondocumentation.
Summary
WehaveexploredsomeofthefunctionalityofmanymodulesinthePythonStandardLibrary.ItishighlyrecommendedtobrowsethroughthePythonStandardLibrarydocumentationtogetanideaofallthemodulesthatareavailable.
StandardLibrary
92
MoreSofarwehavecoveredamajorityofthevariousaspectsofPythonthatyouwilluse.Inthischapter,wewillcoversomemoreaspectsthatwillmakeourknowledgeofPythonmorewell-rounded.
Passingtuplesaround
Everwishedyoucouldreturntwodifferentvaluesfromafunction?Youcan.Allyouhavetodoisuseatuple.
>>>defget_error_details():
...return(2,'details')
...
>>>errnum,errstr=get_error_details()
>>>errnum
2
>>>errstr
'details'
Noticethattheusageof a,b=<someexpression>interpretstheresultoftheexpressionasatuplewithtwovalues.
ThisalsomeansthefastestwaytoswaptwovariablesinPythonis:
>>>a=5;b=8
>>>a,b
(5,8)
>>>a,b=b,a
>>>a,b
(8,5)
SpecialMethods
Therearecertainmethodssuchasthe __init__and __del__methodswhichhavespecialsignificanceinclasses.
Specialmethodsareusedtomimiccertainbehaviorsofbuilt-intypes.Forexample,ifyouwanttousethe x[key]indexingoperationforyourclass(justlikeyouuseitforlistsandtuples),thenallyouhavetodoisimplementthe __getitem__()methodandyourjobisdone.Ifyouthinkaboutit,thisiswhatPythondoesforthe listclassitself!
Someusefulspecialmethodsarelistedinthefollowingtable.Ifyouwanttoknowaboutallthespecialmethods,seethemanual.
__init__(self,...)
Thismethodiscalledjustbeforethenewlycreatedobjectisreturnedforusage.__del__(self)
Calledjustbeforetheobjectisdestroyed(whichhasunpredictabletiming,soavoidusingthis)__str__(self)
Calledwhenweusethe printfunctionorwhen str()isused.__lt__(self,other)
Calledwhenthelessthanoperator(<)isused.Similarly,therearespecialmethodsforalltheoperators(+,>,etc.)__getitem__(self,key)
Calledwhen x[key]indexingoperationisused.
More
94
__len__(self)
Calledwhenthebuilt-in len()functionisusedforthesequenceobject.
SingleStatementBlocks
Wehaveseenthateachblockofstatementsissetapartfromtherestbyitsownindentationlevel.Well,thereisonecaveat.Ifyourblockofstatementscontainsonlyonesinglestatement,thenyoucanspecifyitonthesamelineof,say,aconditionalstatementorloopingstatement.Thefollowingexampleshouldmakethisclear:
>>>flag=True
>>>ifflag:print('Yes')
...
Yes
Noticethatthesinglestatementisusedin-placeandnotasaseparateblock.Although,youcanusethisformakingyourprogramsmaller,Istronglyrecommendavoidingthisshort-cutmethod,exceptforerrorchecking,mainlybecauseitwillbemucheasiertoaddanextrastatementifyouareusingproperindentation.
LambdaForms
A lambdastatementisusedtocreatenewfunctionobjects.Essentially,the lambdatakesaparameterfollowedbyasingleexpression.Lambdabecomesthebodyofthefunction.Thevalueofthisexpressionisreturnedbythenewfunction.
Example(saveas more_lambda.py):
points=[{'x':2,'y':3},
{'x':4,'y':1}]
points.sort(key=lambdai:i['y'])
print(points)
Output:
$pythonmore_lambda.py
[{'y':1,'x':4},{'y':3,'x':2}]
HowItWorks
Noticethatthe sortmethodofa listcantakea keyparameterwhichdetermineshowthelistissorted(usuallyweknowonlyaboutascendingordescendingorder).Inourcase,wewanttodoacustomsort,andforthatweneedtowriteafunction.Insteadofwritingaseparate defblockforafunctionthatwillgetusedinonlythisoneplace,weusealambdaexpressiontocreateanewfunction.
ListComprehension
Listcomprehensionsareusedtoderiveanewlistfromanexistinglist.Supposeyouhavealistofnumbersandyouwanttogetacorrespondinglistwithallthenumbersmultipliedby2onlywhenthenumberitselfisgreaterthan2.Listcomprehensionsareidealforsuchsituations.
Example(saveas more_list_comprehension.py):
listone=[2,3,4]
listtwo=[2*iforiinlistoneifi>2]
More
95
print(listtwo)
Output:
$pythonmore_list_comprehension.py
[6,8]
HowItWorks
Here,wederiveanewlistbyspecifyingthemanipulationtobedone( 2*i)whensomeconditionissatisfied( ifi>2).Notethattheoriginallistremainsunmodified.
Theadvantageofusinglistcomprehensionsisthatitreducestheamountofboilerplatecoderequiredwhenweuseloopstoprocesseachelementofalistandstoreitinanewlist.
ReceivingTuplesandDictionariesinFunctionsThereisaspecialwayofreceivingparameterstoafunctionasatupleoradictionaryusingthe *or **prefixrespectively.Thisisusefulwhentakingvariablenumberofargumentsinthefunction.
>>>defpowersum(power,*args):
...'''Returnthesumofeachargumentraisedtothespecifiedpower.'''
...total=0
...foriinargs:
...total+=pow(i,power)
...returntotal
...
>>>powersum(2,3,4)
25
>>>powersum(2,10)
100
Becausewehavea *prefixonthe argsvariable,allextraargumentspassedtothefunctionarestoredin argsasatuple.Ifa**prefixhadbeenusedinstead,theextraparameterswouldbeconsideredtobekey/valuepairsofadictionary.
TheassertstatementThe assertstatementisusedtoassertthatsomethingistrue.Forexample,ifyouareverysurethatyouwillhaveatleastoneelementinalistyouareusingandwanttocheckthis,andraiseanerrorifitisnottrue,then assertstatementisidealinthissituation.Whentheassertstatementfails,an AssertionErrorisraised.The pop()methodremovesandreturnsthelastitemfromthelist.
>>>mylist=['item']
>>>assertlen(mylist)>=1
>>>mylist.pop()
'item'
>>>assertlen(mylist)>=1
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
AssertionError
The assertstatementshouldbeusedjudiciously.Mostofthetime,itisbettertocatchexceptions,eitherhandletheproblemordisplayanerrormessagetotheuserandthenquit.
More
96
Decorators
Decoratorsareashortcuttoapplyingwrapperfunctions.Thisishelpfulto"wrap"functionalitywiththesamecodeoverandoveragain.Forexample,Icreateda retrydecoratorformyselfthatIcanjustapplytoanyfunctionandifanyexceptionisthrownduringarun,itisretriedagain,tillamaximumof5timesandwithadelaybetweeneachretry.Thisisespeciallyusefulforsituationswhereyouaretryingtomakeanetworkcalltoaremotecomputer:
fromtimeimportsleep
fromfunctoolsimportwraps
importlogging
logging.basicConfig()
log=logging.getLogger("retry")
defretry(f):
@wraps(f)
defwrapper_function(*args,**kwargs):
MAX_ATTEMPTS=5
forattemptinrange(1,MAX_ATTEMPTS+1):
try:
returnf(*args,**kwargs)
exceptException:
log.exception("Attempt%s/%sfailed:%s",
attempt,
MAX_ATTEMPTS,
(args,kwargs))
sleep(10*attempt)
log.critical("All%sattemptsfailed:%s",
MAX_ATTEMPTS,
(args,kwargs))
returnwrapper_function
counter=0
@retry
defsave_to_database(arg):
print("Writetoadatabaseormakeanetworkcalloretc.")
print("Thiswillbeautomaticallyretriedifexceptionisthrown.")
globalcounter
counter+=1
#Thiswillthrowanexceptioninthefirstcall
#Andwillworkfineinthesecondcall(i.e.aretry)
ifcounter<2:
raiseValueError(arg)
if__name__=='__main__':
save_to_database("Somebadvalue")
Output:
$pythonmore_decorator.py
Writetoadatabaseormakeanetworkcalloretc.
Thiswillbeautomaticallyretriedifexceptionisthrown.
ERROR:retry:Attempt1/5failed:(('Somebadvalue',),{})
Traceback(mostrecentcalllast):
File"more_decorator.py",line14,inwrapper_function
returnf(*args,**kwargs)
File"more_decorator.py",line39,insave_to_database
raiseValueError(arg)
ValueError:Somebadvalue
Writetoadatabaseormakeanetworkcalloretc.
More
97
Thiswillbeautomaticallyretriedifexceptionisthrown.
HowItWorks
See:
Video:PythonDecoratorsMadeEasyhttp://www.ibm.com/developerworks/linux/library/l-cpdecor.htmlhttp://toumorokoshi.github.io/dry-principles-through-python-decorators.html
DifferencesbetweenPython2andPython3
See:
"Six"libraryPortingtoPython3ReduxbyArminPython3experiencebyPyDannyOfficialDjangoGuidetoPortingtoPython3DiscussiononWhataretheadvantagestopython3.x?
SummaryWehavecoveredsomemorefeaturesofPythoninthischapterandyetwehaven'tcoveredallthefeaturesofPython.However,atthisstage,wehavecoveredmostofwhatyouareevergoingtouseinpractice.Thisissufficientforyoutogetstartedwithwhateverprogramsyouaregoingtocreate.
Next,wewilldiscusshowtoexplorePythonfurther.
More
98
WhatNextIfyouhavereadthisbookthoroughlytillnowandpracticedwritingalotofprograms,thenyoumusthavebecomecomfortableandfamiliarwithPython.YouhaveprobablycreatedsomePythonprogramstotryoutstuffandtoexerciseyourPythonskillsaswell.Ifyouhavenotdoneitalready,youshould.Thequestionnowis'WhatNext?'.
Iwouldsuggestthatyoutacklethisproblem:
Createyourowncommand-lineaddress-bookprogramusingwhichyoucanbrowse,add,modify,deleteorsearchforyourcontactssuchasfriends,familyandcolleaguesandtheirinformationsuchasemailaddressand/orphonenumber.Detailsmustbestoredforlaterretrieval.
Thisisfairlyeasyifyouthinkaboutitintermsofallthevariousstuffthatwehavecomeacrosstillnow.Ifyoustillwantdirectionsonhowtoproceed,thenhere'sahint .
Onceyouareabletodothis,youcanclaimtobeaPythonprogrammer.Now,immediatelysendmeanemailthankingmeforthisgreatbook;-).Thisstepisoptionalbutrecommended.Also,pleaseconsiderbuyingaprintedcopytosupportthecontinueddevelopmentofthisbook.
Ifyoufoundthatprogrameasy,here'sanotherone:
Implementthereplacecommand.Thiscommandwillreplaceonestringwithanotherinthelistoffilesprovided.
Thereplacecommandcanbeassimpleorassophisticatedasyouwish,fromsimplestringsubstitutiontolookingforpatterns(regularexpressions).
NextProjectsIfyoufoundaboveprogramseasytocreate,thenlookatthiscomprehensivelistofprojectsandtrywritingyourownprograms:https://github.com/thekarangoel/Projects#numbers(thesamelistisalsoatMartyr2'sMegaProjectList).
Alsosee:
ExercisesforProgrammers:57ChallengestoDevelopYourCodingSkillsIntermediatePythonProjects.
ExampleCodeThebestwaytolearnaprogramminglanguageistowritealotofcodeandreadalotofcode:
PythonCookbookisanextremelyvaluablecollectionofrecipesortipsonhowtosolvecertainkindsofproblemsusingPython.Thisisamust-readforeveryPythonuser.PythonModuleoftheWeekisanotherexcellentmust-readguidetotheStandardLibrary.
Advice
TheHitchhiker'sGuidetoPython!TheElementsofPythonStylePythonBigPicture"WritingIdiomaticPython"ebook(paid)
1
WhatNext
99
Videos
FullStackWebDevelopmentwithFlaskPyVideo
QuestionsandAnswers
OfficialPythonDosandDon'tsOfficialPythonFAQNorvig'slistofInfrequentlyAskedQuestionsPythonInterviewQ&AStackOverflowquestionstaggedwithpython
Tutorials
HiddenfeaturesofPythonWhat'stheonecodesnippet/pythontrick/etcdidyouwishyouknewwhenyoulearnedpython?Awaretek'scomprehensivelistofPythontutorials
Discussion
IfyouarestuckwithaPythonproblem,anddon'tknowwhomtoask,thenthepython-tutorlististhebestplacetoaskyourquestion.
Makesureyoudoyourhomeworkbytryingtosolvingtheproblemyourselffirstandasksmartquestions.
NewsIfyouwanttolearnwhatisthelatestintheworldofPython,thenfollowtheOfficialPythonPlanet.
InstallinglibrariesThereareahugenumberofopensourcelibrariesatthePythonPackageIndexwhichyoucanuseinyourownprograms.
Toinstallandusetheselibraries,youcanusepip.
CreatingaWebsite
LearnFlasktocreateyourownwebsite.Someresourcestogetstarted:
FlaskOfficialQuickstartTheFlaskMega-TutorialExampleFlaskProjects
GraphicalSoftware
WhatNext
100
SupposeyouwanttocreateyourowngraphicalprogramsusingPython.ThiscanbedoneusingaGUI(GraphicalUserInterface)librarywiththeirPythonbindings.BindingsarewhatallowyoutowriteprogramsinPythonandusethelibrarieswhicharethemselveswritteninCorC++orotherlanguages.
TherearelotsofchoicesforGUIusingPython:
Kivy
http://kivy.orgPyGTK
ThisisthePythonbindingfortheGTK+toolkitwhichisthefoundationuponwhichGNOMEisbuilt.GTK+hasmanyquirksinusagebutonceyoubecomecomfortable,youcancreateGUIappsfast.TheGladegraphicalinterfacedesignerisindispensable.Thedocumentationisyettoimprove.GTK+workswellonGNU/LinuxbutitsporttoWindowsisincomplete.YoucancreatebothfreeaswellasproprietarysoftwareusingGTK+.Togetstarted,readthePyGTKtutorial.
PyQt
ThisisthePythonbindingfortheQttoolkitwhichisthefoundationuponwhichtheKDEisbuilt.QtisextremelyeasytouseandverypowerfulespeciallyduetotheQtDesignerandtheamazingQtdocumentation.PyQtisfreeifyouwanttocreateopensource(GPL'ed)softwareandyouneedtobuyitifyouwanttocreateproprietaryclosedsourcesoftware.StartingwithQt4.5youcanuseittocreatenon-GPLsoftwareaswell.Togetstarted,readaboutPySide.
wxPython
ThisisthePythonbindingsforthewxWidgetstoolkit.wxPythonhasalearningcurveassociatedwithit.However,itisveryportableandrunsonGNU/Linux,Windows,Macandevenembeddedplatforms.TherearemanyIDEsavailableforwxPythonwhichincludeGUIdesignersaswellsuchasSPE(Stani'sPythonEditor)andthewxGladeGUIbuilder.YoucancreatefreeaswellasproprietarysoftwareusingwxPython.Togetstarted,readthewxPythontutorial.
SummaryofGUITools
Formorechoices,seetheGuiProgrammingwikipageattheofficialpythonwebsite.
Unfortunately,thereisnoonestandardGUItoolforPython.Isuggestthatyouchooseoneoftheabovetoolsdependingonyoursituation.ThefirstfactoriswhetheryouarewillingtopaytouseanyoftheGUItools.ThesecondfactoriswhetheryouwanttheprogramtorunonlyonWindowsoronMacandGNU/Linuxorallofthem.Thethirdfactor,ifGNU/Linuxisachosenplatform,iswhetheryouareaKDEorGNOMEuseronGNU/Linux.
Foramoredetailedandcomprehensiveanalysis,seePage26ofthe'ThePythonPapers,Volume3,Issue1'(PDF).
VariousImplementations
Thereareusuallytwopartsaprogramminglanguage-thelanguageandthesoftware.Alanguageishowyouwritesomething.Thesoftwareiswhatactuallyrunsourprograms.
WehavebeenusingtheCPythonsoftwaretorunourprograms.ItisreferredtoasCPythonbecauseitiswrittenintheClanguageandistheClassicalPythoninterpreter.
TherearealsoothersoftwarethatcanrunyourPythonprograms:
Jython
APythonimplementationthatrunsontheJavaplatform.ThismeansyoucanuseJavalibrariesandclassesfromwithinPythonlanguageandvice-versa.
IronPython
APythonimplementationthatrunsonthe.NETplatform.Thismeansyoucanuse.NETlibrariesandclassesfrom
WhatNext
101
withinPythonlanguageandvice-versa.PyPy
APythonimplementationwritteninPython!Thisisaresearchprojecttomakeitfastandeasytoimprovetheinterpretersincetheinterpreteritselfiswritteninadynamiclanguage(asopposedtostaticlanguagessuchasC,JavaorC#intheabovethreeimplementations)
TherearealsootherssuchasCLPython-aPythonimplementationwritteninCommonLispandBrythonwhichisanimplementationontopofaJavaScriptinterpreterwhichcouldmeanthatyoucanusePython(insteadofJavaScript)towriteyourweb-browser("Ajax")programs.
Eachoftheseimplementationshavetheirspecializedareaswheretheyareuseful.
FunctionalProgramming(foradvancedreaders)
Whenyoustartwritinglargerprograms,youshoulddefinitelylearnmoreaboutafunctionalapproachtoprogrammingasopposedtotheclass-basedapproachtoprogrammingthatwelearnedintheobject-orientedprogrammingchapter:
FunctionalProgrammingHowtobyA.M.KuchlingFunctionalprogrammingchapterin'DiveIntoPython'bookFunctionalProgrammingwithPythonpresentationFuncylibraryPyToolzlibrary
SummaryWehavenowcometotheendofthisbookbut,astheysay,thisisthethebeginningoftheend!.YouarenowanavidPythonuserandyouarenodoubtreadytosolvemanyproblemsusingPython.Youcanstartautomatingyourcomputertodoallkindsofpreviouslyunimaginablethingsorwriteyourowngamesandmuchmuchmore.So,getstarted!
.Createaclasstorepresenttheperson'sinformation.Useadictionarytostorepersonobjectswiththeirnameasthekey.Usethepicklemoduletostoretheobjectspersistentlyonyourharddisk.Usethedictionarybuilt-inmethodstoadd,deleteandmodifythepersons.↩
1
WhatNext
102
Appendix:FLOSSNOTE:Pleasenotethatthissectionwaswrittenin2003,sosomeofthiswillsoundquainttoyou:-)
"Free/LibreandOpenSourceSoftware",inshort,FLOSSisbasedontheconceptofacommunity,whichitselfisbasedontheconceptofsharing,andparticularlythesharingofknowledge.FLOSSarefreeforusage,modificationandredistribution.
Ifyouhavealreadyreadthisbook,thenyouarealreadyfamiliarwithFLOSSsinceyouhavebeenusingPythonallalongandPythonisanopensourcesoftware!
HerearesomeexamplesofFLOSStogiveanideaofthekindofthingsthatcommunitysharingandbuildingcancreate:
Linux:ThisisaFLOSSOSkernelusedintheGNU/Linuxoperatingsystem.Linux,thekernel,wasstartedbyLinusTorvaldsasastudent.AndroidisbasedonLinux.AnywebsiteyouusethesedayswillmostlyberunningonLinux.
Ubuntu:Thisisacommunity-drivendistribution,sponsoredbyCanonicalanditisthemostpopularGNU/Linuxdistributiontoday.ItallowsyoutoinstallaplethoraofFLOSSavailableandallthisinaneasy-to-useandeasy-to-installmanner.Bestofall,youcanjustrebootyourcomputerandrunGNU/LinuxofftheCD!ThisallowsyoutocompletelytryoutthenewOSbeforeinstallingitonyourcomputer.However,Ubuntuisnotentirelyfreesoftware;itcontainsproprietarydrivers,firmware,andapplications.
LibreOffice:Thisisanexcellentcommunity-drivenanddevelopedofficesuitewithawriter,presentation,spreadsheetanddrawingcomponentsamongotherthings.ItcanevenopenandeditMSWordandMSPowerPointfileswithease.Itrunsonalmostallplatformsandisentirelyfree,libreandopensourcesoftware.
MozillaFirefox:Thisisthebestwebbrowser.Itisblazinglyfastandhasgainedcriticalacclaimforitssensibleandimpressivefeatures.Theextensionsconceptallowsanykindofpluginstobeused.
Mono:ThisisanopensourceimplementationoftheMicrosoft.NETplatform.Itallows.NETapplicationstobecreatedandrunonGNU/Linux,Windows,FreeBSD,MacOSandmanyotherplatformsaswell.
Apachewebserver:Thisisthepopularopensourcewebserver.Infact,itisthemostpopularwebserverontheplanet!Itrunsnearlymorethanhalfofthewebsitesoutthere.Yes,that'sright-Apachehandlesmorewebsitesthanallthecompetition(includingMicrosoftIIS)combined.
VLCPlayer:ThisisavideoplayerthatcanplayanythingfromDivXtoMP3toOggtoVCDsandDVDsto...whosaysopensourceain'tfun?;-)
Thislistisjustintendedtogiveyouabriefidea-therearemanymoreexcellentFLOSSoutthere,suchasthePerllanguage,PHPlanguage,Drupalcontentmanagementsystemforwebsites,PostgreSQLdatabaseserver,TORCSracinggame,KDevelopIDE,Xine-themovieplayer,VIMeditor,Quanta+editor,Bansheeaudioplayer,GIMPimageeditingprogram,...Thislistcouldgoonforever.
TogetthelatestbuzzintheFLOSSworld,checkoutthefollowingwebsites:
OMG!Ubuntu!WebUpd8DistroWatchPlanetDebian
VisitthefollowingwebsitesformoreinformationonFLOSS:
GitHubExploreCodeTriageSourceForgeFreshMeat
Appendix:FLOSS
103
Appendix:ColophonAlmostallofthesoftwarethatIhaveusedinthecreationofthisbookareFLOSS.
BirthoftheBook
Inthefirstdraftofthisbook,IhadusedRedHat9.0Linuxasthefoundationofmysetupandinthesixthdraft,IusedFedoraCore3Linuxasthebasisofmysetup.
Initially,IwasusingKWordtowritethebook(asexplainedinthehistorylesson).
TeenageYears
Later,IswitchedtoDocBookXMLusingKatebutIfoundittootedious.So,IswitchedtoOpenOfficewhichwasjustexcellentwiththelevelofcontrolitprovidedforformattingaswellasthePDFgeneration,butitproducedverysloppyHTMLfromthedocument.
Finally,IdiscoveredXEmacsandIrewrotethebookfromscratchinDocBookXML(again)afterIdecidedthatthisformatwasthelongtermsolution.
Inthesixthdraft,IdecidedtouseQuanta+todoalltheediting.ThestandardXSLstylesheetsthatcamewithFedoraCore3Linuxwerebeingused.However,IhadwrittenaCSSdocumenttogivecolorandstyletotheHTMLpages.Ihadalsowrittenacrudelexicalanalyzer,inPythonofcourse,whichautomaticallyprovidessyntaxhighlightingtoalltheprogramlistings.
Fortheseventhdraft,IwasusingMediaWikiasthebasisofmysetup.Iusedtoediteverythingonlineandthereaderscandirectlyread/edit/discusswithinthewikiwebsite,butIendedupspendingmoretimefightingspamthanwriting.
Fortheeightdraft,IusedVim,Pandoc,andMacOSX.
Fortheninthdraft,IswitchedtoAsciiDocformatandusedEmacs24.3,tomorrowtheme,FiraMonofontandadoc-modetowrite.
Now
2016:IgottiredofseveralminorrenderingissuesinAsciiDoctor,likethe ++in C/C++woulddisappearanditwashardtokeeptrackofescapingsuchminorthings.Plus,IhadbecomereluctanttoeditthetextbecauseofthecomplexAsciidocformat.
Forthetenthdraft,IswitchedtowritinginMarkdown+GitBookformat,usingtheSpacemacseditor.
Nov2020:SinceGitbookabandonedtheiropensourcesoftware,migratedtoHonkit,acommunity-maintainedforkofGitbooklegacy.
AbouttheAuthor
Seehttps://swaroopch.com/about
Appendix:About
105
Appendix:HistoryLessonIfirststartedwithPythonwhenIneededtowriteaninstallerforsoftwareIhadwrittencalled'Diamond'sothatIcouldmaketheinstallationeasy.IhadtochoosebetweenPythonandPerlbindingsfortheQtlibrary.IdidsomeresearchonthewebandIcameacrossanarticlebyEricS.Raymond,afamousandrespectedhacker,wherehetalkedabouthowPythonhadbecomehisfavoriteprogramminglanguage.IalsofoundoutthatthePyQtbindingsweremorematurecomparedtoPerl-Qt.So,IdecidedthatPythonwasthelanguageforme.
Then,IstartedsearchingforagoodbookonPython.Icouldn'tfindany!IdidfindsomeO'Reillybooksbuttheywereeithertooexpensiveorweremorelikeareferencemanualthanaguide.So,IsettledforthedocumentationthatcamewithPython.However,itwastoobriefandsmall.ItdidgiveagoodideaaboutPythonbutwasnotcomplete.ImanagedwithitsinceIhadpreviousprogrammingexperience,butitwasunsuitablefornewbies.
AboutsixmonthsaftermyfirstbrushwithPython,Iinstalledthe(then)latestRedHat9.0LinuxandIwasplayingaroundwithKWord.IgotexcitedaboutitandsuddenlygottheideaofwritingsomestuffonPython.Istartedwritingafewpagesbutitquicklybecame30pageslong.Then,Ibecameseriousaboutmakingitmoreusefulinabookform.Afteralotofrewrites,ithasreachedastagewhereithasbecomeausefulguidetolearningthePythonlanguage.Iconsiderthisbooktobemycontributionandtributetotheopensourcecommunity.
ThisbookstartedoutasmypersonalnotesonPythonandIstillconsideritinthesameway,althoughI'vetakenalotofefforttomakeitmorepalatabletoothers:)
Inthetruespiritofopensource,Ihavereceivedlotsofconstructivesuggestions,criticismsandfeedbackfromenthusiasticreaderswhichhashelpedmeimprovethisbookalot.
StatusOfTheBookThebookneedsthehelpofitsreaderssuchasyourselvestopointoutanypartsofthebookwhicharenotgood,notcomprehensibleoraresimplywrong.Pleasewritetothemainauthorortherespectivetranslatorswithyourcommentsandsuggestions.
Appendix:RevisionHistoryNoversionchange
06Nov2020MigratedfromabandonedGitBooktocommunity-maintainedHonkit,aforkofGitBooklegacy
4.0
19Jan2016SwitchedbacktoPython3SwitchedbacktoMarkdown,usingGitBookandSpacemacs
3.0
31Mar2014RewrittenforPython2usingAsciiDocandadoc-mode.
2.1
03Aug2013RewrittenusingMarkdownandJasonBlevins'MarkdownMode
2.0
Appendix:RevisionHistory
106
20Oct2012RewritteninPandocformat,thankstomywifewhodidmostoftheconversionfromtheMediawikiformatSimplifyingtext,removingnon-essentialsectionssuchas nonlocalandmetaclasses
1.90
04Sep2008andstillinprogressRevivalafteragapof3.5years!RewritingforPython3.0Rewriteusinghttp://www.mediawiki.org[MediaWiki](again)
1.20
13Jan2005CompleterewriteusingQuanta+onFedoraCore3withlotofcorrectionsandupdates.Manynewexamples.RewrotemyDocBooksetupfromscratch.
1.15
28Mar2004Minorrevisions
1.12
16Mar2004Additionsandcorrections
1.10
09Mar2004Moretypocorrections,thankstomanyenthusiasticandhelpfulreaders.
1.00
08Mar2004Aftertremendousfeedbackandsuggestionsfromreaders,Ihavemadesignificantrevisionstothecontentalongwithtypocorrections.
0.99
22Feb2004Addedanewchapteronmodules.Addeddetailsaboutvariablenumberofargumentsinfunctions.
0.98
16Feb2004WroteaPythonscriptandCSSstylesheettoimproveXHTMLoutput,includingacrude-yet-functionallexicalanalyzerforautomaticVIM-likesyntaxhighlightingoftheprogramlistings.
0.97
13Feb2004Anothercompletelyrewrittendraft,inDocBookXML(again).Bookhasimprovedalot-itismorecoherentandreadable.
0.93
25Jan2004AddedIDLEtalkandmoreWindows-specificstuff
0.92
05Jan2004Changestofewexamples.
0.91
30Dec2003Correctedtypos.Improvisedmanytopics.
Appendix:RevisionHistory
107
0.90
18Dec2003Added2morechapters.OpenOfficeformatwithrevisions.
0.60
21Nov2003Fullyrewrittenandexpanded.
0.20
20Nov2003Correctedsometyposanderrors.
0.15
20Nov2003ConvertedtoDocBookXMLwithXEmacs.
0.10
14Nov2003InitialdraftusingKWord.
Appendix:RevisionHistory
108
TranslationsTherearemanytranslationsofthebookavailableindifferenthumanlanguages,thankstomanytirelessvolunteers!
Ifyouwanttohelpwiththesetranslations,pleaseseethelistofvolunteersandlanguagesbelowanddecideifyouwanttostartanewtranslationorhelpinexistingtranslationprojects.
Ifyouplantostartanewtranslation,pleasereadtheTranslationhow-to.
ArabicBelowisthelinkfortheArabicversion.ThankstoAshrafAliKhalaffortranslatingthebook,youcanreadthewholebookonlineathttp://www.khaledhosny.org/byte-of-python/index.htmloryoucandownloaditfromsourceforge.netformoreinfoseehttp://itwadi.com/byteofpython_arabi.
AzerbaijaniJahangirShabiyev([email protected])hasvolunteeredtotranslatethebooktoAzerbaijani.Thetranslationisinprogressathttps://www.gitbook.com/book/jahangir-sh/piton-sancmasi
BrazilianPortugueseTherearetwotranslationsinvariouslevelsofcompletionandaccessibility.Theoldertranslationisnowmissing/lost,andnewertranslationisincomplete.
SamuelDiasNeto([email protected])madethefirstBrazilianPortuguesetranslation(oldertranslation)ofthisbookwhenPythonwasin2.3.5version.Thisisnolongerpubliclyaccessible.
RodrigoAmaral([email protected])hasvolunteeredtotranslatethebooktoBrazilianPortuguese,(newertranslation)whichstillremainstobecompleted.
CatalanMoisesGomez([email protected])hasvolunteeredtotranslatethebooktoCatalan.Thetranslationisinprogress.
MoisèsGómez-Iamadeveloperandalsoateacherofprogramming(normallyforpeoplewithoutanypreviousexperience).
SometimeagoIneededtolearnhowtoprograminPython,andSwaroop'sworkwasreallyhelpful.Clear,concise,andcompleteenough.JustwhatIneeded.
Afterthisexperience,Ithoughtsomeotherpeopleinmycountrycouldtakebenefitfromittoo.ButEnglishlanguagecanbeabarrier.
So,whynottrytotranslateit?AndIdidforapreviousversionofBoP.
Imycountrytherearetwoofficiallanguages.IselectedtheCatalanlanguageassumingthatotherswilltranslateittothemorewidespreadSpanish.
Chinese
Appendix:Translations
109
In2017whichisafter11years,MoLun([email protected])re-translatedthebookfromthebeginningbasedonVersion4.0.AndthetranslationisstoragedinGitHubandGitbook.HeiskeepingfollowthistranslatededitionandreadytofixitifthereisanywrongormistakeinthetranslatedBoP.
The2017translationeditionisavailableinhttps://bop.molun.net.
MoLunSays:
IamacommonjournalismstudentfromCYU,Beijing.Andactually,IamanabsolutenewbieinPythonprogrammingwhenIstarttotranslatethisbook.Initially,itwasjustawhim,butwhenIdonethiswork,Irealizedthatadecisiontriggeredbyinteresthadpromptedmetogosofar.
Withthehelpofmypredecessors’translationsandthevastamountofinformationprovidedbythedevelopedInternet,andwiththehelpofmyfriends,Iprudentlypresentedthistranslationedition.IjusthopemytranslationworkwillhelpothernewcomersinlearningPython.
Atthesametime,Iamalwayswaitingformytranslationofthecommentsandsuggestions,andreadytochangeorimprovethissuperficialwork.
EarlierChinesetranslation
In2005,ShenJieyuantranslatedthisbookwithversion1.20toChineseandpublishedittotheInternet.ThisisthefirstChineseedition.InBoPofficialsite,hewascalledJuanShen,withEmailadderssorion_val@163.comThiseditionhasbeendisseminatedonthenetworkwidely,andthelinksprovidedbyBoPofficialsitearenotavailableanymore,sothatitsoriginalsourceisunabletofind.Thereforeinherecan’tprovideacertainaddress.Butyoucantrytosearchkeywordslike“Python”tofindacopy.
JuanShensays:
IamapostgraduateatWirelessTelecommunicationGraduateSchool,BeijingUniversityofTechnology,ChinaPR.Mycurrentresearchinterestisonthesynchronization,channelestimationandmulti-userdetectionofmulticarrierCDMAsystem.Pythonismymajorprogramminglanguagefordailysimulationandresearchjob,withthehelpofPythonNumeric,actually.IlearnedPythonjusthalfayearbefore,butasyoucansee,it'sreallyeasy-understanding,easy-to-useandproductive.JustaswhatisensuredinSwaroop'sbook,'It'smyfavoriteprogramminglanguagenow'.
'AByteofPython'ismytutorialtolearnPython.It'sclearandeffectivetoleadyouintoaworldofPythonintheshortesttime.It'snottoolong,butefficientlycoversalmostallimportantthingsinPython.Ithink'AByteofPython'shouldbestronglyrecommendablefornewbiesastheirfirstPythontutorial.JustdedicatemytranslationtothepotentialmillionsofPythonusersinChina.
ChineseTraditional
FredLin([email protected])hasvolunteeredtotranslatethebooktoChineseTraditional.
Itisavailableathttp://code.google.com/p/zhpy/wiki/ByteOfZhpy.
Anexcitingfeatureofthistranslationisthatitalsocontainstheexecutablechinesepythonsourcessidebysidewiththeoriginalpythonsources.
FredLin-I'mworkingasanetworkfirmwareengineeratDeltaNetwork,andI'malsoacontributorofTurboGearswebframework.
Asapythonevangelist(:-p),Ineedsomematerialtopromotepythonlanguage.Ifound'AByteofPython'hitthesweetpointforbothnewbiesandexperiencedprogrammers.'AByteofPython'elaboratesthepythonessentialswithaffordablesize.
Thetranslationareoriginallybasedonsimplifiedchineseversion,andsoonalotofrewriteweremadetofitthecurrentwikiversionandthequalityofreading.
Appendix:Translations
110
Therecentchinesetraditionalversionalsofeaturedwithexecutablechinesepythonsources,whichareachievedbymynew'zhpy'(pythoninchinese)project(launchfromAug07).
zhpy(pronounce(Z.H.?,orzippy)buildalayeruponpythontotranslateorinteractwithpythoninchinese(TraditionalorSimplified).Thisprojectismainlyaimedforeducation.
French
Gregory([email protected])hasvolunteeredtotranslatethebooktoFrench.
GérardLabadie([email protected])hascompletedtotranslatethebooktoFrench.
Thistranslationwaslaterportedtothemarkdownformat,updatedtomatchthelastversionofthebook,andpublishedonGitBookbyRomainGilliotte([email protected]).
Itcanbefoundathttps://rgilliotte.gitbook.io/byte-of-python/
GermanLutzHorn([email protected]),BerndHengelein([email protected])andChristophZwerschke([email protected])havevolunteeredtotranslatethebooktoGerman.
Translationcanbefoundathttp://cito.github.io/byte_of_python/
LutzHornsays:
I'm32yearsoldandhaveadegreeofMathematicsfromUniversityofHeidelberg,Germany.CurrentlyI'mworkingasasoftwareengineeronapubliclyfundedprojecttobuildawebportalforallthingsrelatedtocomputerscienceinGermany.ThemainlanguageIuseasaprofessionalisJava,butItrytodoasmuchaspossiblewithPythonbehindthescenes.EspeciallytextanalysisandconversionisveryeasywithPython.I'mnotveryfamiliarwithGUItoolkits,sincemostofmyprogrammingisaboutwebapplications,wheretheuserinterfaceisbuildusingJavaframeworkslikeStruts.CurrentlyItrytomakemoreuseofthefunctionalprogrammingfeaturesofPythonandofgenerators.AftertakingashortlookintoRuby,Iwasveryimpressedwiththeuseofblocksinthislanguage.GenerallyIlikethedynamicnatureoflanguageslikePythonandRubysinceitallowsmetodothingsnotpossibleinmorestaticlanguageslikeJava.I'vesearchedforsomekindofintroductiontoprogramming,suitabletoteachacompletenon-programmer.I'vefoundthebook'HowtoThinkLikeaComputerScientist:LearningwithPython',and'DiveintoPython'.Thefirstisgoodforbeginnersbuttolongtotranslate.Thesecondisnotsuitableforbeginners.Ithink'AByteofPython'fallsnicelybetweenthese,sinceitisnottoolong,writtentothepoint,andatthesametimeverboseenoughtoteachanewbie.Besidesthis,IlikethesimpleDocBookstructure,whichmakestranslatingthetextagenerationtheoutputinvariousformatsacharm.
BerndHengeleinsays:
Lutzandmearegoingtodothegermantranslationtogether.Wejuststartedwiththeintroandprefacebutwewillkeepyouinformedabouttheprogresswemake.Ok,nowsomepersonalthingsaboutme.Iam34yearsoldandplayingwithcomputerssincethe1980's,whenthe"CommodoreC64"ruledthenurseries.AfterstudyingcomputerscienceIstartedworkingasasoftwareengineer.CurrentlyIamworkinginthefieldofmedicalimagingforamajorgermancompany.AlthoughC++isthemainlanguageI(haveto)useformydailywork,Iamconstantlylookingfornewthingstolearn.LastyearIfellinlovewithPython,whichisawonderfullanguage,bothforitspossibilitiesanditsbeauty.Ireadsomewhereinthenetaboutaguywhosaidthathelikespython,becausethecodelookssobeautiful.Inmyopinionhe'sabsolutlyright.AtthetimeIdecidedtolearnpython,Inoticedthatthereisverylittlegooddocumentationingermanavailable.WhenIcameacrossyourbookthespontaneousideaofagermantranslationcrossedmymind.Luckily,Lutzhadthesameideaandwecannowdividethework.Iamlookingforwardtoagoodcooperation!
Appendix:Translations
111
Greek
TheGreekUbuntuCommunitytranslatedthebookinGreek,foruseinouron-lineasynchronousPythonlessonsthattakeplaceinourforums.Contact@savvasradevicformoreinformation.
Indonesian
Daniel([email protected])istranslatingthebooktoIndonesianathttp://python.or.id/moin.cgi/ByteofPython.
WisnuPriyambodo([email protected])alsohasvolunteeredtotranslatethebooktoIndonesian.
Also,BagusAjiSantoso([email protected])hasvolunteered.
Italian(first)
EnricoMorelli([email protected])andMassimoLucci([email protected])havevolunteeredtotranslatethebooktoItalian.
TheItaliantranslationispresentathttp://www.gentoo.it/Programmazione/byteofpython.
MassimoLucciandEnricoMorelli-weareworkingattheUniversityofFlorence(Italy)-ChemistryDepartment.I(Massimo)asserviceengineerandsystemadministratorforNuclearMagneticResonanceSpectrometers;EnricoasserviceengineerandsystemadministratorforourCEDandparallel/clusteredsystems.Weareprogrammingonpythonsinceaboutsevenyears,wehadexperienceworkingwithLinuxplatformssincetenyears.InItalyweareresponsibleandadministratorforwww.gentoo.itwebsiteforGentoo/Linuxdistrubutionandwww.nmr.it(nowunderconstruction)forNuclearMagneticResonanceapplicationsandCongressOrganizationandManagements.That'sall!WeareimpressedbythesmartlanguageusedonyourBookandwethinkthisisessentialforapproachingthePythontonewusers(wearethinkingabouthundredofstudentsandresearcherworkingonourlabs).
Italian(second)
AnItaliantranslationhasbeencreatedbyCalvinaBice&colleaguesathttp://besthcgdropswebsite.com/translate/a-byte-of-python/.
Japanese
ShunroDozono([email protected])istranslatingthebooktoJapanese.
Korean
Epsimatt(2019)
EpsimatthasstartedanewKoreantranslation:
Readonlineathttps://epsimatt.gitbook.io/byte-of-python/Followprogressathttps://github.com/epsimatt/byte-of-python/issues/16
Older
JeongbinPark([email protected])hastranslatedthebooktoKorean-https://github.com/pjb7687/byte_of_python
Appendix:Translations
112
IamJeongbinPark,currentlyworkingasaBiophysics&BioinformaticsresearcherinKorea.
Ayearago,Iwaslookingforagoodtutorial/guideforPythontointroduceittomycolleagues,becauseusingPythoninsuchresearchfieldsisbecominginevitableduetotheuserbaseisgrowingmoreandmore.
ButatthattimeonlyfewPythonbooksareavailableinKorean,soIdecidedtotranslateyourebookbecauseitlookslikeoneofthebestguidesthatIhaveeverread!
Currently,thebookisalmostcompletelytranslatedinKorean,exceptsomeofthetextinintroductionchapterandtheappendixes.
Thankyouagainforwritingsuchagoodguide!
MongolianAriunsanaaTunjin([email protected])hasvolunteeredtotranslatethebooktoMongolian.
UpdateonNov22,2009:Ariunsanaaisonthevergeofcompletingthetranslation.
Norwegian(bokmål)
EirikVågeskarisahighschoolstudentatSandvikavideregåendeskoleinNorway,abloggerandcurrentlytranslatingthebooktoNorwegian(bokmål).
EirikVågeskar:Ihavealwayswantedtoprogram,butbecauseIspeakasmalllanguage,thelearningprocesswasmuchharder.MosttutorialsandbooksarewritteninverytechnicalEnglish,somosthighschoolgraduateswillnotevenhavethevocabularytounderstandwhatthetutorialisabout.WhenIdiscoveredthisbook,allmyproblemsweresolved."AByteofPython"usedsimplenon-technicallanguagetoexplainaprogramminglanguagethatisjustassimple,andthesetwothingsmakelearningPythonfun.Afterreadinghalfofthebook,Idecidedthatthebookwasworthtranslating.Ihopethetranslationwillhelppeoplewhohavefoundthemselfinthesamesituationasme(especiallyyoungpeople),andmaybehelpspreadinterestforthelanguageamongpeoplewithlesstechnicalknowledge.
Polish
DominikKozaczko([email protected])hasvolunteeredtotranslatethebooktoPolish.Translationisinprogressandit'smainpageisavailablehere:UkąśPythona.
Update:ThetranslationiscompleteandreadyasofOct2,2009.ThankstoDominik,histwostudentsandtheirfriendfortheirtimeandeffort!
DominikKozaczko-I'maComputerScienceandInformationTechnologyteacher.
Portuguese
ArturWeber([email protected])hascompletedatranslationofthisbooktoPortuguese(asofFeb21,2018)athttps://www.homeyou.com/~edu/introducao.
ArturWeber:MystudentsstudyatthePolytechnicfacultyinEcologicalUniversityinthecityofCuritiba(Brazil)andsomeofthemareinterestedindifferentpapers.
Astheyarewritingcourseandacademicpapers,theyalwayslookforinterestingarticlesandpages.Ialsodomybesttofindinterestingmaterialswhichcanbethesourcesfortheiruniversityworks.
Appendix:Translations
113
IfoundthematerialsfromyoursiteusefulforsomeofmystudentswhoarewritingpapersbasedonprogrammingonPython.Actually,thatiswhyImadeadecisiontoperformaPortuguesetranslationtoletmystudentswhodon'tknowEnglishreadexcitingarticlesintheirmothertongue(inPortuguese).
Romanian
Paul-SebastianManole([email protected])hasvolunteeredtotranslatethisbooktoRomanian.
Paul-SebastianManole-I'masecondyearComputerSciencestudentatSpiruHaretUniversity,hereinRomania.I'mmoreofaself-taughtprogrammeranddecidedtolearnanewlanguage,Python.Thewebtoldmetherewasnobetterwaytodosobutread''AByteofPython''.That'showpopularthisbookis(congratulationstotheauthorforwritingsuchaneasytoreadbook).IstartedlikingPythonsoIdecidedtohelptranslatethelatestversionofSwaroop'sbookinRomanian.AlthoughIcouldbetheonewiththefirstinitiative,I'mjustonevolunteersoifyoucanhelp,pleasejoinme.
Russian
VladimirSmolyar([email protected])hascompletedaRussiantranslationathttp://wombat.org.ua/AByteOfPython/.
Ukranian
AverkievAndrey([email protected])hasvolunteeredtotranslatethebooktoRussian,andperhapsUkranian(timepermitting).
Serbian
"BugSpice"([email protected])hascompletedaSerbiantranslation:
Thisdownloadlinkisnolongeraccessible.
Moredetailsathttp://forum.ubuntu-rs.org/Thread-zagrljaj-pitona.
Slovak
AlbertioWard([email protected])hastranslatedthebooktoSlovakathttp://www.fatcow.com/edu/python-swaroopch-sl/:
Weareanon-profitorganizationcalled"Translationforeducation".Werepresentagroupofpeople,mainlystudentsandprofessors,oftheSlavonicUniversity.Herearestudentsfromdifferentdepartments:linguistics,chemistry,biology,etc.WetrytofindinterestingpublicationsontheInternetthatcanberelevantforusandouruniversitycolleagues.Sometimeswefindarticlesbyourselves;othertimesourprofessorshelpuschoosethematerialfortranslation.Afterobtainingpermissionfromauthorswetranslatearticlesandposttheminourblogwhichisavailableandaccessibletoourcolleaguesandfriends.Thesetranslatedpublicationsoftenhelpstudentsintheirdailystudyroutine.
SpanishAlfonsodelaGuardaReyes([email protected]),GustavoEcheverria([email protected]),DavidCrespoArroyo([email protected])andCristianBermudezSerna([email protected])havevolunteeredtotranslatethebooktoSpanish.
GustavoEcheverriasays:
Appendix:Translations
114
IworkasasoftwareengineerinArgentina.IusemostlyC#and.NettechnologiesatworkbutstrictlyPythonorRubyinmypersonalprojects.IknewPythonmanyyearsagoandIgotstuckinmediately.NotsolongafterknowingPythonIdiscoveredthisbookandithelpedmetolearnthelanguage.ThenIvolunteeredtotranslatethebooktoSpanish.Now,afterreceivingsomerequests,I'vebeguntotranslate"AByteofPython"withthehelpofMaximilianoSoler.
CristianBermudezSernasays:
IamstudentofTelecommunicationsengineeringattheUniversityofAntioquia(Colombia).Monthsago,istartedtolearnPythonandfoundthiswonderfulbook,soivolunteeredtogettheSpanishtranslation.
SwedishMikaelJacobsson([email protected])hasvolunteeredtotranslatethebooktoSwedish.
TurkishTürkerSEZER([email protected])andBugraCakir([email protected])havevolunteeredtotranslatethebooktoTurkish."WhereisTurkishversion?Bitsedeokusak."
Appendix:Translations
115
TranslationHow-to1. Thefullsourceofthebookisavailablefromhttps://github.com/swaroopch/byte-of-python.2. Pleaseforktherepository.3. Then,fetchtherepositorytoyourcomputer.YouneedtoknowhowtouseGittodothat.4. ReadtheHonkitdocumentation,esp.theMarkdownsection.5. Starteditingthe .mdfilestotranslatetoyourlocallanguage.6. SeeINSTALL.mdonhowtogeneratethewebsite,PDF,EPUB.
Appendix:TranslationHow-to
116
FeedbackThebookneedsthehelpofitsreaderssuchasyourselvestopointoutanypartsofthebookwhicharenotgood,notcomprehensibleoraresimplywrong.Pleasewritetothemainauthorortherespectivetranslatorswithyourcommentsandsuggestions.
Feedback
117