Byte of Python
description
Transcript of Byte of Python
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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
AByteofPython
2
AByteofPython"AByteofPython"isafreebookonprogrammingusingthePythonlanguage.ItservesasatutorialorguidetothePythonlanguageforabeginneraudience.Ifallyouknowaboutcomputersishowtosavetextfiles,thenthisisthebookforyou.
ForPythonversion3ThisbookwillteachyoutousePythonversion3.TherewillalsobeguidanceforyoutoadapttotheolderandmorecommonPythonversion2inthebook.
WhoreadsAByteofPython?Herearewhatpeoplearesayingaboutthebook:
Thisisthebestbeginner'stutorialI'veeverseen!Thankyouforyoureffort.--WaltMichalik
Thebestthingifoundwas"AByteofPython",whichissimplyabrilliantbookforabeginner.It'swellwritten,theconceptsarewellexplainedwithselfevidentexamples.--JoshuaRobin
Excellentgentleintroductiontoprogramming#Pythonforbeginners--ShanRajasekaran
Bestnewbieguidetopython--NicksonKaigi
starttolovepythonwitheverysinglepageread--HerbertFeutl
perfectbeginnersguideforpython,willgiveukeytounlockmagicalworldofpython--Dilip
Ishouldbedoingmyactual"work"butjustfound"AByteofPython".Agreatguidewithgreatexamples.--BiologistJohn
RecentlystartedreadingaByteofpython.Awesomework.Andthattooforfree.Highlyrecommendedforaspiringpythonistas.--Mangesh
AByteofPython,writtenbySwaroop.(thisisthebookI'mcurrentlyreading).Probablythebesttostartwith,andprobablythebestintheworldforeverynewbieorevenamoreexperienceduser.--Apostolos
AByteofPython
3Introduction
EnjoyingReading#ByteOfPythonby@swaroopchbestbookever--YuvrajSharma
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
AByteofPython
4Introduction
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
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
AByteofPython
5Introduction
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
AByteofPython
6Introduction
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.YourbookwassowellputtogetherthatIfoundverylittleinitIcouldn'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
AByteofPython
7Introduction
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.
AcademicCoursesThisbookis/wasbeingusedasinstructionalmaterialinvariouseducationalinstitutions:
'PrinciplesofProgrammingLanguages'courseatVrijeUniversiteit,Amsterdam'BasicConceptsofComputing'courseatUniversityofCalifornia,Davis'ProgrammingWithPython'courseatHarvardUniversity'IntroductiontoProgramming'courseatUniversityofLeeds
AByteofPython
8Introduction
'IntroductiontoApplicationProgramming'courseatBostonUniversity'InformationTechnologySkillsforMeteorology'courseatUniversityofOklahoma'Geoprocessing'courseatMichiganStateUniversity'MultiAgentSemanticWebSystems'courseattheUniversityofEdinburgh'IntroductiontoComputerScienceandProgramming'atMITOpenCourseWare'BasicprogrammingattheFacultyofSocialSciences,UniversityofLjubljana,Slovenia'--AlešŽibernasays"I(andmypredecessor)havebeenusingyourbookasthemainliteratureforthiscourse"
LicenseThisbookislicensedunderaCreativeCommonsAttribution-ShareAlike4.0InternationalLicense.
Thismeans:
YouarefreetoSharei.e.tocopy,distributeandtransmitthisbookYouarefreetoRemixi.e.tomakechangestothisbook(especiallytranslations)Youarefreetouseitforcommercialpurposes
Pleasenote:
Pleasedonotsellelectronicorprintedcopiesofthebookunlessyouhaveclearlyandprominentlymentionedinthedescriptionthatthesecopiesarenotfromtheoriginalauthorofthisbook.Attributionmustbeshownintheintroductorydescriptionandfrontpageofthedocumentbylinkingbacktohttp://python.swaroopch.com/andclearlyindicatingthattheoriginaltextcanbefetchedfromthislocation.Allthecode/scriptsprovidedinthisbookislicensedunderthe3-clauseBSDLicenseunlessotherwisenoted.
ReadNowYoucanreaditonlineathttp://python.swaroopch.com/
BuyTheBookAprintedhardcopyofthebookcanbepurchasedathttp://www.swaroopch.com/buybook/foryourofflinereadingpleasure,andtosupportthecontinueddevelopmentandimprovementofthisbook.
AByteofPython
9Introduction
DownloadVisithttps://www.gitbook.com/book/swaroopch/byte-of-python/detailsforthefollowingtypesofdownloads:
PDF(fordesktopreading,etc.)EPUB(foriPhone/iPad,ebookreaders,etc.)Mobi(forKindle)
Visithttps://github.com/swaroopch/byte-of-pythonfortherawcontent(forsuggestingcorrections,changes,translating,etc.)
ReadthebookinyournativelanguageIfyouareinterestedinreadingorcontributingtranslationsofthisbooktootherhumanlanguages,pleaseseeTranslations.
AByteofPython
10Introduction
DedicationToKalyanVarmaandmanyotherseniorsatPESITwhointroducedustoGNU/Linuxandtheworldofopensource.
TothememoryofAtulChitnis,afriendandguidewhoshallbemissedgreatly.
TothepioneerswhomadetheInternethappen.Thisbookwasfirstwrittenin2003.Itstillremainspopular,thankstothenatureofsharingknowledgeontheInternetasenvisionedbythepioneers.
AByteofPython
11Dedication
PrefacePythonisprobablyoneofthefewprogramminglanguageswhichisbothsimpleandpowerful.Thisisgoodforbeginnersaswellasforexperts,andmoreimportantly,isfuntoprogramwith.Thisbookaimstohelpyoulearnthiswonderfullanguageandshowhowtogetthingsdonequicklyandpainlessly-ineffect'TheAnti-venomtoyourprogrammingproblems'.
WhoThisBookIsForThisbookservesasaguideortutorialtothePythonprogramminglanguage.Itismainlytargetedatnewbies.Itisusefulforexperiencedprogrammersaswell.
Theaimisthatifallyouknowaboutcomputersishowtosavetextfiles,thenyoucanlearnPythonfromthisbook.Ifyouhavepreviousprogrammingexperience,thenyoucanalsolearnPythonfromthisbook.
Ifyoudohavepreviousprogrammingexperience,youwillbeinterestedinthedifferencesbetweenPythonandyourfavoriteprogramminglanguage-Ihavehighlightedmanysuchdifferences.Alittlewarningthough,Pythonissoongoingtobecomeyourfavoriteprogramminglanguage!
OfficialWebsiteTheofficialwebsiteofthebookishttp://python.swaroopch.com/whereyoucanreadthewholebookonline,downloadthelatestversionsofthebook,buyaprintedhardcopyandalsosendmefeedback.
SomethingToThinkAboutTherearetwowaysofconstructingasoftwaredesign:onewayistomakeitsosimplethatthereareobviouslynodeficiencies;theotheristomakeitsocomplicatedthattherearenoobviousdeficiencies.--C.A.R.Hoare
Successinlifeisamatternotsomuchoftalentandopportunityasofconcentrationandperseverance.--C.W.Wendte
AByteofPython
12Preface
AboutPythonPythonisoneofthoserarelanguageswhichcanclaimtobebothsimpleandpowerful.Youwillfindyourselfpleasantlysurprisedtoseehoweasyitistoconcentrateonthesolutiontotheproblemratherthanthesyntaxandstructureofthelanguageyouareprogrammingin.
TheofficialintroductiontoPythonis:
Pythonisaneasytolearn,powerfulprogramminglanguage.Ithasefficienthigh-leveldatastructuresandasimplebuteffectiveapproachtoobject-orientedprogramming.Python'selegantsyntaxanddynamictyping,togetherwithitsinterpretednature,makeitanideallanguageforscriptingandrapidapplicationdevelopmentinmanyareasonmostplatforms.
Iwilldiscussmostofthesefeaturesinmoredetailinthenextsection.
StorybehindthenameGuidovanRossum,thecreatorofthePythonlanguage,namedthelanguageaftertheBBCshow"MontyPython'sFlyingCircus".Hedoesn'tparticularlylikesnakesthatkillanimalsforfoodbywindingtheirlongbodiesaroundthemandcrushingthem.
FeaturesofPython
Simple
Pythonisasimpleandminimalisticlanguage.ReadingagoodPythonprogramfeelsalmostlikereadingEnglish,althoughverystrictEnglish!Thispseudo-codenatureofPythonisoneofitsgreateststrengths.Itallowsyoutoconcentrateonthesolutiontotheproblemratherthanthelanguageitself.
EasytoLearn
Asyouwillsee,Pythonisextremelyeasytogetstartedwith.Pythonhasanextraordinarilysimplesyntax,asalreadymentioned.
FreeandOpenSource
AByteofPython
13AboutPython
PythonisanexampleofaFLOSS(Free/LibréandOpenSourceSoftware).Insimpleterms,youcanfreelydistributecopiesofthissoftware,readitssourcecode,makechangestoit,andusepiecesofitinnewfreeprograms.FLOSSisbasedontheconceptofacommunitywhichsharesknowledge.ThisisoneofthereasonswhyPythonissogood-ithasbeencreatedandisconstantlyimprovedbyacommunitywhojustwanttoseeabetterPython.
High-levelLanguage
WhenyouwriteprogramsinPython,youneverneedtobotheraboutthelow-leveldetailssuchasmanagingthememoryusedbyyourprogram,etc.
Portable
Duetoitsopen-sourcenature,Pythonhasbeenportedto(i.e.changedtomakeitworkon)manyplatforms.AllyourPythonprogramscanworkonanyoftheseplatformswithoutrequiringanychangesatallifyouarecarefulenoughtoavoidanysystem-dependentfeatures.
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!
AByteofPython
14AboutPython
ObjectOriented
Pythonsupportsprocedure-orientedprogrammingaswellasobject-orientedprogramming.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.
AByteofPython
15AboutPython
Rememberthatonceyouhaveproperlyunderstoodandlearntouseoneversion,youcaneasilylearnthedifferencesandusetheotherone.ThehardpartislearningprogrammingandunderstandingthebasicsofPythonlanguageitself.Thatisourgoalinthisbook,andonceyouhaveachievedthatgoal,youcaneasilyusePython2orPython3dependingonyoursituation.
FordetailsondifferencesbetweenPython2andPython3,see:
ThefutureofPython2PortingPython2CodetoPython3WritingcodethatrunsunderbothPython2and3SupportingPython3:Anin-depthguide
WhatProgrammersSayYoumayfinditinterestingtoreadwhatgreathackerslikeESRhavetosayaboutPython:
EricS.Raymondistheauthorof"TheCathedralandtheBazaar"andisalsothepersonwhocoinedthetermOpenSource.HesaysthatPythonhasbecomehisfavoriteprogramminglanguage.ThisarticlewastherealinspirationformyfirstbrushwithPython.BruceEckelistheauthorofthefamous'ThinkinginJava'and'ThinkinginC++'books.HesaysthatnolanguagehasmadehimmoreproductivethanPython.HesaysthatPythonisperhapstheonlylanguagethatfocusesonmakingthingseasierfortheprogrammer.Readthecompleteinterviewformoredetails.PeterNorvigisawell-knownLispauthorandDirectorofSearchQualityatGoogle(thankstoGuidovanRossumforpointingthatout).HesaysthatwritingPythonislikewritinginpseudocode.HesaysthatPythonhasalwaysbeenanintegralpartofGoogle.YoucanactuallyverifythisstatementbylookingattheGoogleJobspagewhichlistsPythonknowledgeasarequirementforsoftwareengineers.
AByteofPython
16AboutPython
InstallationWhenwereferto"Python3"inthisbook,wewillbereferringtoanyversionofPythonequaltoorgreaterthanversionPython3.5.1.
InstallationonWindowsVisithttps://www.python.org/downloads/anddownloadthelatestversion.Atthetimeofthiswriting,itwasPython3.5.1TheinstallationisjustlikeanyotherWindows-basedsoftware.
CAUTION:MakesureyoucheckoptionAddPython3.5toPATH.
Tochangeinstalllocation,clickonCustomizeinstallation,thenNextandenterC:\python35asinstalllocation.
Ifnotchecked,checkAddPythontoenvironmentvariables.ThisdoesthesamethingasAddPython3.5toPATHonthefirstinstallscreen.
YoucanchoosetoinstallLauncherforallusersornot,itdoesnotmattermuch.LauncherisusedtoswitchbetweendifferentversionsofPythoninstalled.
Ifyourpathwasnotsetcorrectly,thenfollowthesestepstofixit.Otherwise,gotoRunningPythonpromptonWindows.
NOTE:Forpeoplewhoalreadyknowprogramming,ifyouarefamiliarwithDocker,checkoutPythoninDockerandDockeronWindows.
DOSPrompt
IfyouwanttobeabletousePythonfromtheWindowscommandlinei.e.theDOSprompt,thenyouneedtosetthePATHvariableappropriately.
ForWindows2000,XP,2003,clickonControlPanel->System->Advanced->EnvironmentVariables.ClickonthevariablenamedPATHintheSystemVariablessection,thenselectEditandadd;C:\Python35(pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Ofcourse,usetheappropriatedirectoryname.
ForolderversionsofWindows,openthefileC:\AUTOEXEC.BATandaddthelinePATH=%PATH%;C:\Python35andrestartthesystem.ForWindowsNT,usetheAUTOEXEC.NTfile.
AByteofPython
17Installation
ForWindowsVista:
ClickStartandchooseControlPanelClickSystem,ontherightyou'llsee"Viewbasicinformationaboutyourcomputer"Ontheleftisalistoftasks,thelastofwhichisAdvancedsystemsettings.Clickthat.TheAdvancedtaboftheSystemPropertiesdialogboxisshown.ClicktheEnvironmentVariablesbuttononthebottomright.InthelowerboxtitledSystemVariablesscrolldowntoPathandclicktheEditbutton.Changeyourpathasneedbe.Restartyoursystem.Vistadidn'tpickupthesystempathenvironmentvariablechangeuntilIrestarted.
ForWindows7and8:
RightclickonComputerfromyourdesktopandselectPropertiesorclickStartandchooseControlPanel->SystemandSecurity->System.ClickonAdvancedsystemsettingsontheleftandthenclickontheAdvancedtab.AtthebottomclickonEnvironmentVariablesandunderSystemvariables,lookforthePATHvariable,selectandthenpressEdit.GototheendofthelineunderVariablevalueandappend;C:\Python35(pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Ofcourse,usetheappropriatefoldername.Ifthevaluewas%SystemRoot%\system32;Itwillnowbecome%SystemRoot%\system32;C:\Python35
ClickOKandyouaredone.Norestartisrequired,howeveryoumayhavetocloseandreopenthecommandline.
RunningPythonpromptonWindows
ForWindowsusers,youcanruntheinterpreterinthecommandlineifyouhavesetthePATHvariableappropriately.
ToopentheterminalinWindows,clickthestartbuttonandclickRun.Inthedialogbox,typecmdandpress[enter]key.
Then,typepythonandensuretherearenoerrors.
InstallationonMacOSXForMacOSXusers,useHomebrew:brewinstallpython3.
AByteofPython
18Installation
Toverify,opentheterminalbypressing[Command+Space]keys(toopenSpotlightsearch),typeTerminalandpress[enter]key.Now,runpython3andensuretherearenoerrors.
InstallationonGNU/LinuxForGNU/Linuxusers,useyourdistribution'spackagemanagertoinstallPython3,e.g.onDebian&Ubuntu:sudoapt-getupdate&&sudoapt-getinstallpython3.
Toverify,opentheterminalbyopeningtheTerminalapplicationorbypressingAlt+F2andenteringgnome-terminal.Ifthatdoesn'twork,pleasereferthedocumentationofyourparticularGNU/Linuxdistribution.Now,runpython3andensuretherearenoerrors.
YoucanseetheversionofPythononthescreenbyrunning:
$python3-V
Python3.5.1
NOTE:$isthepromptoftheshell.Itwillbedifferentforyoudependingonthesettingsoftheoperatingsystemonyourcomputer,henceIwillindicatethepromptbyjustthe$symbol.
CAUTION:Outputmaybedifferentonyourcomputer,dependingontheversionofPythonsoftwareinstalledonyourcomputer.
SummaryFromnowon,wewillassumethatyouhavePythoninstalledonyoursystem.
Next,wewillwriteourfirstPythonprogram.
AByteofPython
19Installation
FirstStepsWewillnowseehowtorunatraditional'HelloWorld'programinPython.Thiswillteachyouhowtowrite,saveandrunPythonprograms.
TherearetwowaysofusingPythontorunyourprogram-usingtheinteractiveinterpreterpromptorusingasourcefile.Wewillnowseehowtousebothofthesemethods.
UsingTheInterpreterPromptOpentheterminalinyouroperatingsystem(asdiscussedpreviouslyintheInstallationchapter)andthenopenthePythonpromptbytypingpython3andpressing[enter]key.
OnceyouhavestartedPython,youshouldsee>>>whereyoucanstarttypingstuff.ThisiscalledthePythoninterpreterprompt.
AtthePythoninterpreterprompt,type:
print("HelloWorld")
followedbythe[enter]key.YoushouldseethewordsHelloWorldprintedtothescreen.
Hereisanexampleofwhatyoushouldbeseeing,whenusingaMacOSXcomputer.ThedetailsaboutthePythonsoftwarewilldifferbasedonyourcomputer,butthepartfromtheprompt(i.e.from>>>onwards)shouldbethesameregardlessoftheoperatingsystem.
>python3
Python3.5.1(default,Jan142016,06:54:11)
[GCC4.2.1CompatibleAppleLLVM7.0.2(clang-700.1.81)]ondarwin
Type"help","copyright","credits"or"license"formoreinformation.
>>>print("HelloWorld")
HelloWorld
NoticethatPythongivesyoutheoutputofthelineimmediately!WhatyoujustenteredisasinglePythonstatement.Weuseprintto(unsurprisingly)printanyvaluethatyousupplytoit.Here,wearesupplyingthetextHelloWorldandthisispromptlyprintedtothescreen.
HowtoQuittheInterpreterPrompt
AByteofPython
20FirstSteps
IfyouareusingaGNU/LinuxorOSXshell,youcanexittheinterpreterpromptbypressing[ctrl+d]orenteringexit()(note:remembertoincludetheparentheses,())followedbythe[enter]key.
IfyouareusingtheWindowscommandprompt,press[ctrl+z]followedbythe[enter]key.
ChoosingAnEditorWecannottypeoutourprogramattheinterpreterprompteverytimewewanttorunsomething,sowehavetosavetheminfilesandcanrunourprogramsanynumberoftimes.
TocreateourPythonsourcefiles,weneedaneditorsoftwarewhereyoucantypeandsave.Agoodprogrammer'seditorwillmakeyourlifeeasierinwritingthesourcefiles.Hence,thechoiceofaneditoriscrucialindeed.Youhavetochooseaneditorasyouwouldchooseacaryouwouldbuy.AgoodeditorwillhelpyouwritePythonprogramseasily,makingyourjourneymorecomfortableandhelpsyoureachyourdestination(achieveyourgoal)inamuchfasterandsaferway.
OneoftheverybasicrequirementsissyntaxhighlightingwhereallthedifferentpartsofyourPythonprogramarecolorizedsothatyoucanseeyourprogramandvisualizeitsrunning.
Ifyouhavenoideawheretostart,IwouldrecommendusingPyCharmEducationalEditionsoftwarewhichisavailableonWindows,MacOSXandGNU/Linux.Detailsinthenextsection.
IfyouareusingWindows,donotuseNotepad-itisabadchoicebecauseitdoesnotdosyntaxhighlightingandalsoimportantlyitdoesnotsupportindentationofthetextwhichisveryimportantinourcaseaswewillseelater.Goodeditorswillautomaticallydothis.
Ifyouareanexperiencedprogrammer,thenyoumustbealreadyusingVimorEmacs.Needlesstosay,thesearetwoofthemostpowerfuleditorsandyouwillbenefitfromusingthemtowriteyourPythonprograms.Ipersonallyusebothformostofmyprograms,andhaveevenwrittenanentirebookonVim.
IncaseyouarewillingtotakethetimetolearnVimorEmacs,thenIhighlyrecommendthatyoudolearntouseeitherofthemasitwillbeveryusefulforyouinthelongrun.However,asImentionedbefore,beginnerscanstartwithPyCharmandfocusthelearningonPythonratherthantheeditoratthismoment.
Toreiterate,pleasechooseapropereditor-itcanmakewritingPythonprogramsmorefunandeasy.
AByteofPython
21FirstSteps
PyCharmPyCharmEducationalEditionisafreeeditorwhichyoucanuseforwritingPythonprograms.
WhenyouopenPyCharm,you'llseethis,clickonCreateNewProject:
SelectPurePython:
AByteofPython
22FirstSteps
Changeuntitledtohelloworldasthelocationoftheproject,youshouldseedetailssimilartothis:
AByteofPython
23FirstSteps
ClicktheCreatebutton.
Right-clickonthehelloworldinthesidebarandselectNew->PythonFile:
AByteofPython
24FirstSteps
Youwillbeaskedtotypethename,typehello:
Youcannowseeafileopenedforyou:
AByteofPython
25FirstSteps
Deletethelinesthatarealreadypresent,andnowtypethefollowing:
print("helloworld")
Nowright-clickonwhatyoutyped(withoutselectingthetext),andclickonRun'hello'.
AByteofPython
26FirstSteps
Youshouldnowseetheoutput(whatitprints)ofyourprogram:
Phew!Thatwasquiteafewstepstogetstarted,buthenceforth,everytimeweaskyoutocreateanewfile,remembertojustright-clickonhelloworldontheleft->New->PythonFileandcontinuethesamestepstotypeandrunasshownabove.
YoucanfindmoreinformationaboutPyCharminthePyCharmQuickstartpage.
Vim1. InstallVim
MacOSXusersshouldinstallmacvimpackageviaHomeBrewWindowsusersshoulddownloadthe"self-installingexecutable"fromVimwebsiteGNU/LinuxusersshouldgetVimfromtheirdistribution'ssoftwarerepositories,e.g.DebianandUbuntuuserscaninstallthevimpackage.
2. Installjedi-vimpluginforautocompletion.3. Installcorrespondingjedipythonpackage:pipinstall-Ujedi
Emacs1. InstallEmacs24+.
MacOSXusersshouldgetEmacsfromhttp://emacsformacosx.comWindowsusersshouldgetEmacsfromhttp://ftp.gnu.org/gnu/emacs/windows/
AByteofPython
27FirstSteps
GNU/LinuxusersshouldgetEmacsfromtheirdistribution'ssoftwarerepositories,e.g.DebianandUbuntuuserscaninstalltheemacs24package.
2. InstallELPY
UsingASourceFileNowlet'sgetbacktoprogramming.Thereisatraditionthatwheneveryoulearnanewprogramminglanguage,thefirstprogramthatyouwriteandrunisthe'HelloWorld'program
-allitdoesisjustsay'HelloWorld'whenyourunit.AsSimonCozens1says,itisthe"traditionalincantationtotheprogramminggodstohelpyoulearnthelanguagebetter."
Startyourchoiceofeditor,enterthefollowingprogramandsaveitashello.py.
IfyouareusingPyCharm,wehavealreadydiscussedhowtorunfromasourcefile.
Forothereditors,openanewfilehello.pyandtypethis:
print("helloworld")
Whereshouldyousavethefile?Toanyfolderforwhichyouknowthelocationofthefolder.Ifyoudon'tunderstandwhatthatmeans,createanewfolderandusethatlocationtosaveandrunallyourPythonprograms:
/tmp/pyonMacOSX/tmp/pyonGNU/LinuxC:\\pyonWindows
Tocreatetheabovefolder(fortheoperatingsystemyouareusing),usethemkdircommandintheterminal,forexample,mkdir/tmp/py.
IMPORTANT:Alwaysensurethatyougiveitthefileextensionof.py,forexample,foo.py.
TorunyourPythonprogram:
1. Openaterminalwindow(seethepreviousInstallationchapteronhowtodothat)2. Changedirectorytowhereyousavedthefile,forexample,cd/tmp/py3. Runtheprogrambyenteringthecommandpythonhello.py.Theoutputisasshown
below.
$pythonhello.py
helloworld
AByteofPython
28FirstSteps
Ifyougottheoutputasshownabove,congratulations!-youhavesuccessfullyrunyourfirstPythonprogram.Youhavesuccessfullycrossedthehardestpartoflearningprogramming,whichis,gettingstartedwithyourfirstprogram!
Incaseyougotanerror,pleasetypetheaboveprogramexactlyasshownaboveandruntheprogramagain.NotethatPythoniscase-sensitivei.e.printisnotthesameasPrint-notethelowercasepintheformerandtheuppercasePinthelatter.Also,ensuretherearenospacesortabsbeforethefirstcharacterineachline-wewillseewhythisisimportantlater.
HowItWorks
APythonprogramiscomposedofstatements.Inourfirstprogram,wehaveonlyonestatement.Inthisstatement,wecalltheprintstatementtowhichwesupplythetext"helloworld".
GettingHelpIfyouneedquickinformationaboutanyfunctionorstatementinPython,thenyoucanusethebuilt-inhelpfunctionality.Thisisveryusefulespeciallywhenusingtheinterpreterprompt.Forexample,runhelp('len')-thisdisplaysthehelpforthelenfunctionwhichisusedtocountnumberofitems.
AByteofPython
29FirstSteps
TIP:Pressqtoexitthehelp.
Similarly,youcanobtaininformationaboutalmostanythinginPython.Usehelp()tolearnmoreaboutusinghelpitself!
Incaseyouneedtogethelpforoperatorslikereturn,thenyouneedtoputthoseinsidequotessuchashelp('return')sothatPythondoesn'tgetconfusedonwhatwe'retryingtodo.
SummaryYoushouldnowbeabletowrite,saveandrunPythonprogramsatease.
NowthatyouareaPythonuser,let'slearnsomemorePythonconcepts.
1.theauthoroftheamazing'BeginningPerl'book↩
AByteofPython
30FirstSteps
BasicsJustprintinghelloworldisnotenough,isit?Youwanttodomorethanthat-youwanttotakesomeinput,manipulateitandgetsomethingoutofit.WecanachievethisinPythonusingconstantsandvariables,andwe'lllearnsomeotherconceptsaswellinthischapter.
CommentsCommentsareanytexttotherightofthe#symbolandismainlyusefulasnotesforthereaderoftheprogram.
Forexample:
print('helloworld')#Notethatprintisafunction
or:
#Notethatprintisafunction
print('helloworld')
Useasmanyusefulcommentsasyoucaninyourprogramto:
explainassumptionsexplainimportantdecisionsexplainimportantdetailsexplainproblemsyou'retryingtosolveexplainproblemsyou'retryingtoovercomeinyourprogram,etc.
Codetellsyouhow,commentsshouldtellyouwhy.
Thisisusefulforreadersofyourprogramsothattheycaneasilyunderstandwhattheprogramisdoing.Remember,thatpersoncanbeyourselfaftersixmonths!
LiteralConstantsAnexampleofaliteralconstantisanumberlike5,1.23,orastringlike'Thisisastring'or"It'sastring!".
AByteofPython
31Basics
Itiscalledaliteralbecauseitisliteral-youuseitsvalueliterally.Thenumber2alwaysrepresentsitselfandnothingelse-itisaconstantbecauseitsvaluecannotbechanged.Hence,allthesearereferredtoasliteralconstants.
NumbersNumbersaremainlyoftwotypes-integersandfloats.
Anexamplesofanintegeris2whichisjustawholenumber.
Examplesoffloatingpointnumbers(orfloatsforshort)are3.23and52.3E-4.TheEnotationindicatespowersof10.Inthiscase,52.3E-4means52.3*10^-4^.
NoteforExperiencedProgrammers
Thereisnoseparatelongtype.Theinttypecanbeanintegerofanysize.
StringsAstringisasequenceofcharacters.Stringsarebasicallyjustabunchofwords.
YouwillbeusingstringsinalmosteveryPythonprogramthatyouwrite,sopayattentiontothefollowingpart.
SingleQuote
Youcanspecifystringsusingsinglequotessuchas'Quotemeonthis'.
Allwhitespacei.e.spacesandtabs,withinthequotes,arepreservedas-is.
DoubleQuotes
Stringsindoublequotesworkexactlythesamewayasstringsinsinglequotes.Anexampleis"What'syourname?".
TripleQuotes
Youcanspecifymulti-linestringsusingtriplequotes-("""or''').Youcanusesinglequotesanddoublequotesfreelywithinthetriplequotes.Anexampleis:
AByteofPython
32Basics
'''Thisisamulti-linestring.Thisisthefirstline.
Thisisthesecondline.
"What'syourname?,"Iasked.
Hesaid"Bond,JamesBond."
'''
StringsAreImmutable
Thismeansthatonceyouhavecreatedastring,youcannotchangeit.Althoughthismightseemlikeabadthing,itreallyisn't.Wewillseewhythisisnotalimitationinthevariousprogramsthatweseelateron.
NoteforC/C++Programmers
ThereisnoseparatechardatatypeinPython.ThereisnorealneedforitandIamsureyouwon'tmissit.
NoteforPerl/PHPProgrammers
Rememberthatsingle-quotedstringsanddouble-quotedstringsarethesame-theydonotdifferinanyway.
Theformatmethod
Sometimeswemaywanttoconstructstringsfromotherinformation.Thisiswheretheformat()methodisuseful.
Savethefollowinglinesasafilestr_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?
HowItWorks
Astringcanusecertainspecificationsandsubsequently,theformatmethodcanbecalledtosubstitutethosespecificationswithcorrespondingargumentstotheformatmethod.
AByteofPython
33Basics
Observethefirstusagewhereweuse{0}andthiscorrespondstothevariablenamewhichisthefirstargumenttotheformatmethod.Similarly,thesecondspecificationis{1}correspondingtoagewhichisthesecondargumenttotheformatmethod.NotethatPythonstartscountingfrom0whichmeansthatfirstpositionisatindex0,secondpositionisatindex1,andsoon.
Noticethatwecouldhaveachievedthesameusingstringconcatenation:
name+'is'+str(age)+'yearsold'
butthatismuchuglieranderror-prone.Second,theconversiontostringwouldbedoneautomaticallybytheformatmethodinsteadoftheexplicitconversiontostringsneededinthiscase.Third,whenusingtheformatmethod,wecanchangethemessagewithouthavingtodealwiththevariablesusedandvice-versa.
Alsonotethatthenumbersareoptional,soyoucouldhavealsowrittenas:
age=20
name='Swaroop'
print('{}was{}yearsoldwhenhewrotethisbook'.format(name,age))
print('Whyis{}playingwiththatpython?'.format(name))
whichwillgivethesameexactoutputasthepreviousprogram.
WhatPythondoesintheformatmethodisthatitsubstituteseachargumentvalueintotheplaceofthespecification.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'))
Output:
0.333
___hello___
SwaroopwroteAByteofPython
AByteofPython
34Basics
Sincewearediscussingformatting,notethatprintalwaysendswithaninvisible"newline"character(\n)sothatrepeatedcallstoprintwillallprintonaseparatelineeach.Topreventthisnewlinecharacterfrombeingprinted,youcanspecifythatitshouldendwithablank:
print('a',end='')
print('b',end='')
Outputis:
ab
Oryoucanendwithaspace:
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'
AByteofPython
35Basics
Anotherusefulescapesequencetoknowisthetab:\t.TherearemanymoreescapesequencesbutIhavementionedonlythemostusefuloneshere.
Onethingtonoteisthatinastring,asinglebackslashattheendofthelineindicatesthatthestringiscontinuedinthenextline,butnonewlineisadded.Forexample:
"Thisisthefirstsentence.\
Thisisthesecondsentence."
isequivalentto
"Thisisthefirstsentence.Thisisthesecondsentence."
RawString
Ifyouneedtospecifysomestringswherenospecialprocessingsuchasescapesequencesarehandled,thenwhatyouneedistospecifyarawstringbyprefixingrorRtothestring.Anexampleis:
r"Newlinesareindicatedby\n"
NoteforRegularExpressionUsers
Alwaysuserawstringswhendealingwithregularexpressions.Otherwise,alotofbackwhackingmayberequired.Forexample,backreferencescanbereferredtoas'\\1'orr'\1'.
VariableUsingjustliteralconstantscansoonbecomeboring-weneedsomewayofstoringanyinformationandmanipulatethemaswell.Thisiswherevariablescomeintothepicture.Variablesareexactlywhatthenameimplies-theirvaluecanvary,i.e.,youcanstoreanythingusingavariable.Variablesarejustpartsofyourcomputer'smemorywhereyoustoresomeinformation.Unlikeliteralconstants,youneedsomemethodofaccessingthesevariablesandhenceyougivethemnames.
IdentifierNaming
AByteofPython
36Basics
Variablesareexamplesofidentifiers.Identifiersarenamesgiventoidentifysomething.Therearesomerulesyouhavetofollowfornamingidentifiers:
Thefirstcharacteroftheidentifiermustbealetterofthealphabet(uppercaseASCIIorlowercaseASCIIorUnicodecharacter)oranunderscore(_).Therestoftheidentifiernamecanconsistofletters(uppercaseASCIIorlowercaseASCIIorUnicodecharacter),underscores(_)ordigits(0-9).Identifiernamesarecase-sensitive.Forexample,mynameandmyNamearenotthesame.NotethelowercasenintheformerandtheuppercaseNinthelatter.Examplesofvalididentifiernamesarei,name_2_3.Examplesofinvalididentifiernamesare2things,thisisspacedout,my-nameand>a1b2_c3.
DataTypesVariablescanholdvaluesofdifferenttypescalleddatatypes.Thebasictypesarenumbersandstrings,whichwehavealreadydiscussed.Inlaterchapters,wewillseehowtocreateourowntypesusingclasses.
ObjectRemember,Pythonreferstoanythingusedinaprogramasanobject.Thisismeantinthegenericsense.Insteadofsaying"thesomething"',wesay"theobject".
NoteforObjectOrientedProgrammingusers:
Pythonisstronglyobject-orientedinthesensethateverythingisanobjectincludingnumbers,stringsandfunctions.
Wewillnowseehowtousevariablesalongwithliteralconstants.Savethefollowingexampleandruntheprogram.
HowtowritePythonprogramsHenceforth,thestandardproceduretosaveandrunaPythonprogramisasfollows:
ForPyCharm
1. OpenPyCharm.2. Createnewfilewiththefilenamementioned.3. Typetheprogramcodegivenintheexample.
AByteofPython
37Basics
4. Right-clickandrunthecurrentfile.
NOTE:Wheneveryouhavetoprovidecommandlinearguments,clickonRun->EditConfigurationsandtypetheargumentsintheScriptparameters:sectionandclicktheOKbutton:
Forothereditors
1. Openyoureditorofchoice.2. Typetheprogramcodegivenintheexample.3. Saveitasafilewiththefilenamementioned.4. Runtheinterpreterwiththecommandpythonprogram.pytoruntheprogram.
Example:UsingVariablesAndLiteralConstants
Typeandrunthefollowingprogram:
#Filename:var.py
i=5
print(i)
i=i+1
print(i)
s='''Thisisamulti-linestring.
Thisisthesecondline.'''
print(s)
AByteofPython
38Basics
Output:
5
6
Thisisamulti-linestring.
Thisisthesecondline.
HowItWorks
Here'showthisprogramworks.First,weassigntheliteralconstantvalue5tothevariableiusingtheassignmentoperator(=).Thislineiscalledastatementbecauseitstatesthatsomethingshouldbedoneandinthiscase,weconnectthevariablenameitothevalue5.Next,weprintthevalueofiusingtheprintstatementwhich,unsurprisingly,justprintsthevalueofthevariabletothescreen.
Thenweadd1tothevaluestorediniandstoreitback.Wethenprintitandexpectedly,wegetthevalue6.
Similarly,weassigntheliteralstringtothevariable+s+andthenprintit.
Noteforstaticlanguageprogrammers
Variablesareusedbyjustassigningthemavalue.Nodeclarationordatatypedefinitionisneeded/used.
LogicalAndPhysicalLineAphysicallineiswhatyouseewhenyouwritetheprogram.AlogicallineiswhatPythonseesasasinglestatement.Pythonimplicitlyassumesthateachphysicallinecorrespondstoalogicalline.
Anexampleofalogicallineisastatementlikeprint'helloworld'-ifthiswasonalinebyitself(asyouseeitinaneditor),thenthisalsocorrespondstoaphysicalline.
Implicitly,Pythonencouragestheuseofasinglestatementperlinewhichmakescodemorereadable.
Ifyouwanttospecifymorethanonelogicallineonasinglephysicalline,thenyouhavetoexplicitlyspecifythisusingasemicolon(;)whichindicatestheendofalogicalline/statement.Forexample:
i=5
print(i)
AByteofPython
39Basics
iseffectivelysameas
i=5;
print(i);
whichisalsosameas
i=5;print(i);
andsameas
i=5;print(i)
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.Youcansee
AByteofPython
40Basics
thisinactionwhenwewriteprogramsusinglistinlaterchapters.
IndentationWhitespaceisimportantinPython.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).Caseswhereyoucanusenewblockswillbedetailedinlaterchapterssuchasthecontrolflow.
Howtoindent
Usefourspacesforindentation.ThisistheofficialPythonlanguagerecommendation.Goodeditorswillautomaticallydothisforyou.Makesureyouuseaconsistentnumberofspacesforindentation,otherwiseyourprogramwillnotrunorwillhaveunexpectedbehavior.
AByteofPython
41Basics
Notetostaticlanguageprogrammers
Pythonwillalwaysuseindentationforblocksandwillneverusebraces.Runfrom__future__importbracestolearnmore.
SummaryNowthatwehavegonethroughmanynitty-grittydetails,wecanmoveontomoreinterestingstuffsuchascontrolflowstatements.Besuretobecomecomfortablewithwhatyouhavereadinthischapter.
AByteofPython
42Basics
OperatorsandExpressionsMoststatements(logicallines)thatyouwritewillcontainexpressions.Asimpleexampleofanexpressionis2+3.Anexpressioncanbebrokendownintooperatorsandoperands.
Operatorsarefunctionalitythatdosomethingandcanberepresentedbysymbolssuchas+orbyspecialkeywords.Operatorsrequiresomedatatooperateonandsuchdataiscalledoperands.Inthiscase,2and3aretheoperands.
OperatorsWewillbrieflytakealookattheoperatorsandtheirusage.
Notethatyoucanevaluatetheexpressionsgivenintheexamplesusingtheinterpreterinteractively.Forexample,totesttheexpression2+3,usetheinteractivePythoninterpreterprompt:
>>>2+3
5
>>>3*5
15
>>>
Hereisaquickoverviewoftheavailableoperators:
+(plus)
Addstwoobjects3+5gives8.'a'+'b'gives'ab'.
-(minus)
Givesthesubtractionofonenumberfromtheother;ifthefirstoperandisabsentitisassumedtobezero.-5.2givesanegativenumberand50-24gives26.
*(multiply)
Givesthemultiplicationofthetwonumbersorreturnsthestringrepeatedthatmanytimes.2*3gives6.'la'*3gives'lalala'.
**(power)
Returnsxtothepowerofy
AByteofPython
43OperatorsandExpressions
3**4gives81(i.e.3*3*3*3)/(divide)
Dividexbyy13/3gives4.333333333333333
//(divideandfloor)
Dividexbyyandroundtheanswerdowntothenearestwholenumber13//3gives4-13//3gives-5
%(modulo)
Returnstheremainderofthedivision13%3gives1.-25.5%2.25gives1.5.
<<(leftshift)
Shiftsthebitsofthenumbertotheleftbythenumberofbitsspecified.(Eachnumberisrepresentedinmemorybybitsorbinarydigitsi.e.0and1)2<<2gives8.2isrepresentedby10inbits.Leftshiftingby2bitsgives1000whichrepresentsthedecimal8.
>>(rightshift)
Shiftsthebitsofthenumbertotherightbythenumberofbitsspecified.11>>1gives5.11isrepresentedinbitsby1011whichwhenrightshiftedby1bitgives101whichisthedecimal5.
&(bit-wiseAND)
Bit-wiseANDofthenumbers5&3gives1.
|(bit-wiseOR)
BitwiseORofthenumbers5|3gives7
(bit-wiseXOR)
BitwiseXORofthenumbers5^3gives6
~(bit-wiseinvert)
Thebit-wiseinversionofxis-(x+1)~5gives-6.Moredetailsathttp://stackoverflow.com/a/11810203
<(lessthan)
Returnswhetherxislessthany.AllcomparisonoperatorsreturnTrueorFalse.
AByteofPython
44OperatorsandExpressions
Notethecapitalizationofthesenames.5<3givesFalseand3<5givesTrue.Comparisonscanbechainedarbitrarily:3<5<7givesTrue.
>(greaterthan)
Returnswhetherxisgreaterthany5>3returnsTrue.Ifbothoperandsarenumbers,theyarefirstconvertedtoacommontype.Otherwise,italwaysreturnsFalse.
<=(lessthanorequalto)
Returnswhetherxislessthanorequaltoyx=3;y=6;x<=yreturnsTrue
>=(greaterthanorequalto)
Returnswhetherxisgreaterthanorequaltoyx=4;y=3;x>=3returnsTrue
==(equalto)
Comparesiftheobjectsareequalx=2;y=2;x==yreturnsTruex='str';y='stR';x==yreturnsFalsex='str';y='str';x==yreturnsTrue
!=(notequalto)
Comparesiftheobjectsarenotequalx=2;y=3;x!=yreturnsTrue
not(booleanNOT)
IfxisTrue,itreturnsFalse.IfxisFalse,itreturnsTrue.x=True;notxreturnsFalse.
and(booleanAND)
xandyreturnsFalseifxisFalse,elseitreturnsevaluationofyx=False;y=True;xandyreturnsFalsesincexisFalse.Inthiscase,Pythonwillnotevaluateysinceitknowsthatthelefthandsideofthe'and'expressionisFalsewhichimpliesthatthewholeexpressionwillbeFalseirrespectiveoftheothervalues.Thisiscalledshort-circuitevaluation.
or(booleanOR)
IfxisTrue,itreturnsTrue,elseitreturnsevaluationofyx=True;y=False;xoryreturnsTrue.Short-circuitevaluationapplieshereaswell.
AByteofPython
45OperatorsandExpressions
ShortcutformathoperationandassignmentItiscommontorunamathoperationonavariableandthenassigntheresultoftheoperationbacktothevariable,hencethereisashortcutforsuchexpressions:
a=2
a=a*3
canbewrittenas:
a=2
a*=3
Noticethatvar=varoperationexpressionbecomesvaroperation=expression.
EvaluationOrderIfyouhadanexpressionsuchas2+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
AByteofPython
46OperatorsandExpressions
<<,>>:Shifts+,-: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)isdefinitelyeasiertounderstandthan2+3*4whichrequiresknowledgeoftheoperatorprecedences.Aswitheverythingelse,theparenthesesshouldbeusedreasonably(donotoverdoit)andshouldnotberedundant,asin(2+(3*4)).
Thereisanadditionaladvantagetousingparentheses-ithelpsustochangetheorderofevaluation.Forexample,ifyouwantadditiontobeevaluatedbeforemultiplicationinanexpression,thenyoucanwritesomethinglike(2+3)*4.
AssociativityOperatorsareusuallyassociatedfromlefttoright.Thismeansthatoperatorswiththesameprecedenceareevaluatedinalefttorightmanner.Forexample,2+3+4isevaluatedas(2+3)+4.
ExpressionsExample(saveasexpression.py):
AByteofPython
47OperatorsandExpressions
length=5
breadth=2
area=length*breadth
print('Areais',area)
print('Perimeteris',2*(length+breadth))
Output:
$pythonexpression.py
Areais10
Perimeteris14
HowItWorks
Thelengthandbreadthoftherectanglearestoredinvariablesbythesamename.Weusethesetocalculatetheareaandperimeteroftherectanglewiththehelpofexpressions.Westoretheresultoftheexpressionlength*breadthinthevariable+area+andthenprintitusingthe+print+function.Inthesecondcase,wedirectlyusethevalueoftheexpression2*(length+breadth)intheprintfunction.
Also,noticehowPythonpretty-printstheoutput.Eventhoughwehavenotspecifiedaspacebetween'Areais'andthevariablearea,Pythonputsitforussothatwegetacleanniceoutputandtheprogramismuchmorereadablethisway(sincewedon'tneedtoworryaboutspacinginthestringsweuseforoutput).ThisisanexampleofhowPythonmakeslifeeasyfortheprogrammer.
SummaryWehaveseenhowtouseoperators,operandsandexpressions-thesearethebasicbuildingblocksofanyprogram.Next,wewillseehowtomakeuseoftheseinourprogramsusingstatements.
AByteofPython
48OperatorsandExpressions
ControlFlowIntheprogramswehaveseentillnow,therehasalwaysbeenaseriesofstatementsfaithfullyexecutedbyPythoninexacttop-downorder.Whatifyouwantedtochangetheflowofhowitworks?Forexample,youwanttheprogramtotakesomedecisionsanddodifferentthingsdependingondifferentsituations,suchasprinting'GoodMorning'or'GoodEvening'dependingonthetimeoftheday?
Asyoumighthaveguessed,thisisachievedusingcontrolflowstatements.TherearethreecontrolflowstatementsinPython-if,forandwhile.
TheifstatementTheifstatementisusedtocheckacondition:iftheconditionistrue,werunablockofstatements(calledtheif-block),elseweprocessanotherblockofstatements(calledtheelse-block).Theelseclauseisoptional.
Example(saveasif.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:
AByteofPython
49Controlflow
$pythonif.py
Enteraninteger:50
No,itisalittlelowerthanthat
Done
$pythonif.py
Enteraninteger:22
No,itisalittlehigherthanthat
Done
$pythonif.py
Enteraninteger:23
Congratulations,youguessedit.
(butyoudonotwinanyprizes!)
Done
HowItWorks
Inthisprogram,wetakeguessesfromtheuserandcheckifitisthenumberthatwehave.Wesetthevariable+number+toanyintegerwewant,say23.Then,wetaketheuser'sguessusingtheinput()function.Functionsarejustreusablepiecesofprograms.We'llreadmoreabouttheminthenextchapter.
Wesupplyastringtothebuilt-ininputfunctionwhichprintsittothescreenandwaitsforinputfromtheuser.Onceweentersomethingandpresskbd:[enter]key,theinput()functionreturnswhatweentered,asastring.Wethenconvertthisstringtoanintegerusingintandthenstoreitinthevariableguess.Actually,theintisaclassbutallyouneedtoknowrightnowisthatyoucanuseittoconvertastringtoaninteger(assumingthestringcontainsavalidintegerinthetext).
Next,wecomparetheguessoftheuserwiththenumberwehavechosen.Iftheyareequal,weprintasuccessmessage.NoticethatweuseindentationlevelstotellPythonwhichstatementsbelongtowhichblock.ThisiswhyindentationissoimportantinPython.Ihopeyouarestickingtothe"consistentindentation"rule.Areyou?
Noticehowtheifstatementcontainsacolonattheend-weareindicatingtoPythonthatablockofstatementsfollows.
Then,wecheckiftheguessislessthanthenumber,andifso,weinformtheuserthattheymustguessalittlehigherthanthat.Whatwehaveusedhereistheelifclausewhichactuallycombinestworelatedifelse-ifelsestatementsintoonecombinedif-elif-elsestatement.Thismakestheprogrameasierandreducestheamountofindentationrequired.
Theelifandelsestatementsmustalsohaveacolonattheendofthelogicallinefollowedbytheircorrespondingblockofstatements(withproperindentation,ofcourse)
AByteofPython
50Controlflow
Youcanhaveanotherifstatementinsidetheif-blockofanifstatementandsoon-thisiscalledanestedifstatement.
Rememberthattheelifandelsepartsareoptional.Aminimalvalidifstatementis:
ifTrue:
print('Yes,itistrue')
AfterPythonhasfinishedexecutingthecompleteifstatementalongwiththeassociatedelifandelseclauses,itmovesontothenextstatementintheblockcontainingtheifstatement.Inthiscase,itisthemainblock(whereexecutionoftheprogramstarts),andthenextstatementistheprint('Done')statement.Afterthis,Pythonseestheendsoftheprogramandsimplyfinishesup.
Eventhoughthisisaverysimpleprogram,Ihavebeenpointingoutalotofthingsthatyoushouldnotice.Alltheseareprettystraightforward(andsurprisinglysimpleforthoseofyoufromC/C++backgrounds).Youwillneedtobecomeawareofallthesethingsinitially,butaftersomepracticeyouwillbecomecomfortablewiththem,anditwillallfeel'natural'toyou.
NoteforC/C++Programmers
ThereisnoswitchstatementinPython.Youcanuseanif..elif..elsestatementtodothesamething(andinsomecases,useadictionarytodoitquickly)
ThewhileStatementThewhilestatementallowsyoutorepeatedlyexecuteablockofstatementsaslongasaconditionistrue.Awhilestatementisanexampleofwhatiscalledaloopingstatement.Awhilestatementcanhaveanoptionalelseclause.
Example(saveaswhile.py):
AByteofPython
51Controlflow
number=23
running=True
whilerunning:
guess=int(input('Enteraninteger:'))
ifguess==number:
print('Congratulations,youguessedit.')
#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.Thisaptlydemonstratestheuseofthewhilestatement.
WemovetheinputandifstatementstoinsidethewhileloopandsetthevariablerunningtoTruebeforethewhileloop.First,wecheckifthevariablerunningisTrueandthenproceedtoexecutethecorrespondingwhile-block.Afterthisblockisexecuted,theconditionisagaincheckedwhichinthiscaseistherunningvariable.Ifitistrue,weexecutethewhile-blockagain,elsewecontinuetoexecutetheoptionalelse-blockandthencontinuetothenextstatement.
AByteofPython
52Controlflow
TheelseblockisexecutedwhenthewhileloopconditionbecomesFalse-thismayevenbethefirsttimethattheconditionischecked.Ifthereisanelseclauseforawhileloop,itisalwaysexecutedunlessyoubreakoutoftheloopwithabreakstatement.
TheTrueandFalsearecalledBooleantypesandyoucanconsiderthemtobeequivalenttothevalue1and0respectively.
NoteforC/C++Programmers
Rememberthatyoucanhaveanelseclauseforthewhileloop.
TheforloopThefor..instatementisanotherloopingstatementwhichiteratesoverasequenceofobjectsi.e.gothrougheachiteminasequence.Wewillseemoreaboutsequencesindetailinlaterchapters.Whatyouneedtoknowrightnowisthatasequenceisjustanorderedcollectionofitems.
Example(saveasfor.py):
foriinrange(1,5):
print(i)
else:
print('Theforloopisover')
Output:
$pythonfor.py
1
2
3
4
Theforloopisover
HowItWorks
Inthisprogram,weareprintingasequenceofnumbers.Wegeneratethissequenceofnumbersusingthebuilt-inrangefunction.
Whatwedohereissupplyittwonumbersandrangereturnsasequenceofnumbersstartingfromthefirstnumberanduptothesecondnumber.Forexample,range(1,5)givesthesequence[1,2,3,4].Bydefault,rangetakesastepcountof1.Ifwesupplyathird
AByteofPython
53Controlflow
numbertorange,thenthatbecomesthestepcount.Forexample,range(1,5,2)gives[1,3].Rememberthattherangeextendsuptothesecondnumberi.e.itdoesnotincludethesecondnumber.
Notethatrange()generatesonlyonenumberatatime,ifyouwantthefulllistofnumbers,calllist()ontherange(),forexample,list(range(5))willresultin[0,1,2,3,4].Listsareexplainedinthedatastructureschapter.
Theforlooptheniteratesoverthisrange-foriinrange(1,5)isequivalenttoforiin[1,2,3,4]whichislikeassigningeachnumber(orobject)inthesequencetoi,oneatatime,andthenexecutingtheblockofstatementsforeachvalueofi.Inthiscase,wejustprintthevalueintheblockofstatements.
Rememberthattheelsepartisoptional.Whenincluded,itisalwaysexecutedonceaftertheforloopisoverunlessa<>statementisencountered.
Rememberthatthefor..inloopworksforanysequence.Here,wehavealistofnumbersgeneratedbythebuilt-inrangefunction,butingeneralwecanuseanykindofsequenceofanykindofobjects!Wewillexplorethisideaindetailinlaterchapters.
NoteforC/C++/Java/C#Programmers
ThePythonforloopisradicallydifferentfromtheC/C++forloop.C#programmerswillnotethattheforloopinPythonissimilartotheforeachloopinC#.Javaprogrammerswillnotethatthesameissimilartofor(inti:IntArray)inJava1.5.
InC/C++,ifyouwanttowritefor(inti=0;i<5;i++),theninPythonyouwritejustforiinrange(0,5).Asyoucansee,theforloopissimpler,moreexpressiveandlesserrorproneinPython.
ThebreakStatementThebreakstatementisusedtobreakoutofaloopstatementi.e.stoptheexecutionofaloopingstatement,eveniftheloopconditionhasnotbecomeFalseorthesequenceofitemshasnotbeencompletelyiteratedover.
Animportantnoteisthatifyoubreakoutofafororwhileloop,anycorrespondingloopelseblockisnotexecuted.
Example(saveasbreak.py):
AByteofPython
54Controlflow
whileTrue:
s=input('Entersomething:')
ifs=='quit':
break
print('Lengthofthestringis',len(s))
print('Done')
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-inlenfunction.
Rememberthatthebreakstatementcanbeusedwiththeforloopaswell.
Swaroop'sPoeticPython
TheinputIhaveusedhereisaminipoemIhavewritten:
Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
ThecontinueStatementThecontinuestatementisusedtotellPythontoskiptherestofthestatementsinthecurrentloopblockandtocontinuetothenextiterationoftheloop.
AByteofPython
55Controlflow
Example(saveascontinue.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
HowItWorks
Inthisprogram,weacceptinputfromtheuser,butweprocesstheinputstringonlyifitisatleast3characterslong.So,weusethebuilt-inlenfunctiontogetthelengthandifthelengthislessthan3,weskiptherestofthestatementsintheblockbyusingthecontinuestatement.Otherwise,therestofthestatementsintheloopareexecuted,doinganykindofprocessingwewanttodohere.
Notethatthecontinuestatementworkswiththeforloopaswell.
SummaryWehaveseenhowtousethethreecontrolflowstatements-if,whileandforalongwiththeirassociatedbreakandcontinuestatements.ThesearesomeofthemostcommonlyusedpartsofPythonandhence,becomingcomfortablewiththemisessential.
Next,wewillseehowtocreateandusefunctions.
AByteofPython
56Controlflow
FunctionsFunctionsarereusablepiecesofprograms.Theyallowyoutogiveanametoablockofstatements,allowingyoutorunthatblockusingthespecifiednameanywhereinyourprogramandanynumberoftimes.Thisisknownascallingthefunction.Wehavealreadyusedmanybuilt-infunctionssuchaslenandrange.
Thefunctionconceptisprobablythemostimportantbuildingblockofanynon-trivialsoftware(inanyprogramminglanguage),sowewillexplorevariousaspectsoffunctionsinthischapter.
Functionsaredefinedusingthedefkeyword.Afterthiskeywordcomesanidentifiernameforthefunction,followedbyapairofparentheseswhichmayenclosesomenamesofvariables,andbythefinalcolonthatendstheline.Nextfollowstheblockofstatementsthatarepartofthisfunction.Anexamplewillshowthatthisisactuallyverysimple:
Example(saveasfunction1.py):
defsay_hello():
#blockbelongingtothefunction
print('helloworld')
#Endoffunction
say_hello()#callthefunction
say_hello()#callthefunctionagain
Output:
$pythonfunction1.py
helloworld
helloworld
HowItWorks
Wedefineafunctioncalledsay_hellousingthesyntaxasexplainedabove.Thisfunctiontakesnoparametersandhencetherearenovariablesdeclaredintheparentheses.Parameterstofunctionsarejustinputtothefunctionsothatwecanpassindifferentvaluestoitandgetbackcorrespondingresults.
Noticethatwecancallthesamefunctiontwicewhichmeanswedonothavetowritethesamecodeagain.
AByteofPython
57Functions
FunctionParametersAfunctioncantakeparameters,whicharevaluesyousupplytothefunctionsothatthefunctioncandosomethingutilisingthosevalues.Theseparametersarejustlikevariablesexceptthatthevaluesofthesevariablesaredefinedwhenwecallthefunctionandarealreadyassignedvalueswhenthefunctionruns.
Parametersarespecifiedwithinthepairofparenthesesinthefunctiondefinition,separatedbycommas.Whenwecallthefunction,wesupplythevaluesinthesameway.Notetheterminologyused-thenamesgiveninthefunctiondefinitionarecalledparameterswhereasthevaluesyousupplyinthefunctioncallarecalledarguments.
Example(saveasfunction_param.py):
defprint_max(a,b):
ifa>b:
print(a,'ismaximum')
elifa==b:
print(a,'isequalto',b)
else:
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,wedefineafunctioncalledprint_maxthatusestwoparameterscalledaandb.Wefindoutthegreaternumberusingasimpleif..elsestatementandthenprintthebiggernumber.
Thefirsttimewecallthefunctionprint_max,wedirectlysupplythenumbersasarguments.Inthesecondcase,wecallthefunctionwithvariablesasarguments.print_max(x,y)causesthevalueofargumentxtobeassignedtoparameteraandthevalueof
AByteofPython
58Functions
argumentytobeassignedtoparameterb.Theprint_maxfunctionworksthesamewayinbothcases.
LocalVariablesWhenyoudeclarevariablesinsideafunctiondefinition,theyarenotrelatedinanywaytoothervariableswiththesamenamesusedoutsidethefunction-i.e.variablenamesarelocaltothefunction.Thisiscalledthescopeofthevariable.Allvariableshavethescopeoftheblocktheyaredeclaredinstartingfromthepointofdefinitionofthename.
Example(saveasfunction_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.
Next,weassignthevalue2tox.Thenamexislocaltoourfunction.So,whenwechangethevalueofxinthefunction,thexdefinedinthemainblockremainsunaffected.
Withthelastprintstatement,wedisplaythevalueofxasdefinedinthemainblock,therebyconfirmingthatitisactuallyunaffectedbythelocalassignmentwithinthepreviouslycalledfunction.
AByteofPython
59Functions
TheglobalstatementIfyouwanttoassignavaluetoanamedefinedatthetopleveloftheprogram(i.e.notinsideanykindofscopesuchasfunctionsorclasses),thenyouhavetotellPythonthatthenameisnotlocal,butitisglobal.Wedothisusingtheglobalstatement.Itisimpossibletoassignavaluetoavariabledefinedoutsideafunctionwithouttheglobalstatement.
Youcanusethevaluesofsuchvariablesdefinedoutsidethefunction(assumingthereisnovariablewiththesamenamewithinthefunction).However,thisisnotencouragedandshouldbeavoidedsinceitbecomesuncleartothereaderoftheprogramastowherethatvariable'sdefinitionis.Usingtheglobalstatementmakesitamplyclearthatthevariableisdefinedinanoutermostblock.
Example(saveasfunction_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
Theglobalstatementisusedtodeclarethatxisaglobalvariable-hence,whenweassignavaluetoxinsidethefunction,thatchangeisreflectedwhenweusethevalueofxinthemainblock.
Youcanspecifymorethanoneglobalvariableusingthesameglobalstatemente.g.globalx,y,z.
AByteofPython
60Functions
DefaultArgumentValuesForsomefunctions,youmaywanttomakesomeparametersoptionalandusedefaultvaluesincasetheuserdoesnotwanttoprovidevaluesforthem.Thisisdonewiththehelpofdefaultargumentvalues.Youcanspecifydefaultargumentvaluesforparametersbyappendingtotheparameternameinthefunctiondefinitiontheassignmentoperator(=)followedbythedefaultvalue.
Notethatthedefaultargumentvalueshouldbeaconstant.Moreprecisely,thedefaultargumentvalueshouldbeimmutable-thisisexplainedindetailinlaterchapters.Fornow,justrememberthis.
Example(saveasfunction_default.py):
defsay(message,times=1):
print(message*times)
say('Hello')
say('World',5)
Output:
$pythonfunction_default.py
Hello
WorldWorldWorldWorldWorld
HowItWorks
Thefunctionnamedsayisusedtoprintastringasmanytimesasspecified.Ifwedon'tsupplyavalue,thenbydefault,thestringisprintedjustonce.Weachievethisbyspecifyingadefaultargumentvalueof1totheparametertimes.
Inthefirstusageofsay,wesupplyonlythestringanditprintsthestringonce.Inthesecondusageofsay,wesupplyboththestringandanargument5statingthatwewanttosaythestringmessage5times.
CAUTION
Onlythoseparameterswhichareattheendoftheparameterlistcanbegivendefaultargumentvaluesi.e.youcannothaveaparameterwithadefaultargumentvalueprecedingaparameterwithoutadefaultargumentvalueinthefunction'sparameterlist.
Thisisbecausethevaluesareassignedtotheparametersbyposition.Forexample,deffunc(a,b=5)isvalid,butdeffunc(a=5,b)isnotvalid.
AByteofPython
61Functions
KeywordArgumentsIfyouhavesomefunctionswithmanyparametersandyouwanttospecifyonlysomeofthem,thenyoucangivevaluesforsuchparametersbynamingthem-thisiscalledkeywordarguments-weusethename(keyword)insteadoftheposition(whichwehavebeenusingallalong)tospecifytheargumentstothefunction.
Therearetwoadvantages-one,usingthefunctioniseasiersincewedonotneedtoworryabouttheorderofthearguments.Two,wecangivevaluestoonlythoseparameterstowhichwewantto,providedthattheotherparametershavedefaultargumentvalues.
Example(saveasfunction_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
HowItWorks
Thefunctionnamedfunchasoneparameterwithoutadefaultargumentvalue,followedbytwoparameterswithdefaultargumentvalues.
Inthefirstusage,func(3,7),theparameteragetsthevalue3,theparameterbgetsthevalue7andcgetsthedefaultvalueof10.
Inthesecondusagefunc(25,c=24),thevariableagetsthevalueof25duetothepositionoftheargument.Then,theparametercgetsthevalueof24duetonamingi.e.keywordarguments.Thevariablebgetsthedefaultvalueof5.
Inthethirdusagefunc(c=50,a=100),weusekeywordargumentsforallspecifiedvalues.Noticethatwearespecifyingthevalueforparametercbeforethatforaeventhoughaisdefinedbeforecinthefunctiondefinition.
VarArgsparameters
AByteofPython
62Functions
Sometimesyoumightwanttodefineafunctionthatcantakeanynumberofparameters,i.e.variablenumberofarguments,thiscanbeachievedbyusingthestars(saveasfunction_varargs.py):
deftotal(initial=5,*numbers,**keywords):
count=initial
fornumberinnumbers:
count+=number
forkeyinkeywords:
count+=keywords[key]
returncount
print(total(10,1,2,3,vegetables=50,fruits=100))
Output:
$pythonfunction_varargs.py
166
HowItWorks
Whenwedeclareastarredparametersuchas*param,thenallthepositionalargumentsfromthatpointtilltheendarecollectedasatuplecalled'param'.
Similarly,whenwedeclareadouble-starredparametersuchas**param,thenallthekeywordargumentsfromthatpointtilltheendarecollectedasadictionarycalled'param'.
Wewillexploretuplesanddictionariesinalaterchapter.
ThereturnstatementThereturnstatementisusedtoreturnfromafunctioni.e.breakoutofthefunction.Wecanoptionallyreturnavaluefromthefunctionaswell.
Example(saveasfunction_return.py):
defmaximum(x,y):
ifx>y:
returnx
elifx==y:
return'Thenumbersareequal'
else:
returny
print(maximum(2,3))
AByteofPython
63Functions
Output:
$pythonfunction_return.py
3
HowItWorks
Themaximumfunctionreturnsthemaximumoftheparameters,inthiscasethenumberssuppliedtothefunction.Itusesasimpleif..elsestatementtofindthegreatervalueandthenreturnsthatvalue.
NotethatareturnstatementwithoutavalueisequivalenttoreturnNone.NoneisaspecialtypeinPythonthatrepresentsnothingness.Forexample,itisusedtoindicatethatavariablehasnovalueifithasavalueofNone.
EveryfunctionimplicitlycontainsareturnNonestatementattheendunlessyouhavewrittenyourownreturnstatement.Youcanseethisbyrunningprintsome_function()wherethefunctionsome_functiondoesnotusethereturnstatementsuchas:
defsome_function():
pass
ThepassstatementisusedinPythontoindicateanemptyblockofstatements.
TIP:Thereisabuilt-infunctioncalledmaxthatalreadyimplementsthe'findmaximum'functionality,sousethisbuilt-infunctionwheneverpossible.
DocStringsPythonhasaniftyfeaturecalleddocumentationstrings,usuallyreferredtobyitsshorternamedocstrings.DocStringsareanimportanttoolthatyoushouldmakeuseofsinceithelpstodocumenttheprogrambetterandmakesiteasiertounderstand.Amazingly,wecanevengetthedocstringbackfrom,sayafunction,whentheprogramisactuallyrunning!
Example(saveasfunction_docstring.py):
AByteofPython
64Functions
defprint_max(x,y):
'''Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.'''
#converttointegers,ifpossible
x=int(x)
y=int(y)
ifx>y:
print(x,'ismaximum')
else:
print(y,'ismaximum')
print_max(3,5)
print(print_max.__doc__)
Output:
$pythonfunction_docstring.py
5ismaximum
Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.
HowItWorks
Astringonthefirstlogicallineofafunctionisthedocstringforthatfunction.NotethatDocStringsalsoapplytomodulesandclasseswhichwewilllearnaboutintherespectivechapters.
Theconventionfollowedforadocstringisamulti-linestringwherethefirstlinestartswithacapitalletterandendswithadot.Thenthesecondlineisblankfollowedbyanydetailedexplanationstartingfromthethirdline.Youarestronglyadvisedtofollowthisconventionforallyourdocstringsforallyournon-trivialfunctions.
Wecanaccessthedocstringoftheprint_maxfunctionusingthe__doc__(noticethedoubleunderscores)attribute(namebelongingto)ofthefunction.JustrememberthatPythontreatseverythingasanobjectandthisincludesfunctions.We'lllearnmoreaboutobjectsinthechapteronclasses.
Ifyouhaveusedhelp()inPython,thenyouhavealreadyseentheusageofdocstrings!Whatitdoesisjustfetchthe__doc__attributeofthatfunctionanddisplaysitinaneatmannerforyou.Youcantryitoutonthefunctionabove-justincludehelp(print_max)inyourprogram.Remembertopresstheqkeytoexithelp.
AByteofPython
65Functions
Automatedtoolscanretrievethedocumentationfromyourprograminthismanner.Therefore,Istronglyrecommendthatyouusedocstringsforanynon-trivialfunctionthatyouwrite.ThepydoccommandthatcomeswithyourPythondistributionworkssimilarlytohelp()usingdocstrings.
SummaryWehaveseensomanyaspectsoffunctionsbutnotethatwestillhaven'tcoveredallaspectsofthem.However,wehavealreadycoveredmostofwhatyou'lluseregardingPythonfunctionsonaneverydaybasis.
Next,wewillseehowtouseaswellascreatePythonmodules.
AByteofPython
66Functions
ModulesYouhaveseenhowyoucanreusecodeinyourprogrambydefiningfunctionsonce.Whatifyouwantedtoreuseanumberoffunctionsinotherprogramsthatyouwrite?Asyoumighthaveguessed,theanswerismodules.
Therearevariousmethodsofwritingmodules,butthesimplestwayistocreateafilewitha.pyextensionthatcontainsfunctionsandvariables.
AnothermethodistowritethemodulesinthenativelanguageinwhichthePythoninterpreteritselfwaswritten.Forexample,youcanwritemodulesintheCprogramminglanguageandwhencompiled,theycanbeusedfromyourPythoncodewhenusingthestandardPythoninterpreter.
Amodulecanbeimportedbyanotherprogramtomakeuseofitsfunctionality.ThisishowwecanusethePythonstandardlibraryaswell.First,wewillseehowtousethestandardlibrarymodules.
Example(saveasmodule_using_sys.py):
importsys
print('Thecommandlineargumentsare:')
foriinsys.argv:
print(i)
print('\n\nThePYTHONPATHis',sys.path,'\n')
Output:
$pythonmodule_using_sys.pywearearguments
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
AByteofPython
67Modules
First,weimportthesysmoduleusingtheimportstatement.Basically,thistranslatestoustellingPythonthatwewanttousethismodule.ThesysmodulecontainsfunctionalityrelatedtothePythoninterpreteranditsenvironmenti.e.thesystem.
WhenPythonexecutestheimportsysstatement,itlooksforthesysmodule.Inthiscase,itisoneofthebuilt-inmodules,andhencePythonknowswheretofindit.
Ifitwasnotacompiledmodulei.e.amodulewritteninPython,thenthePythoninterpreterwillsearchforitinthedirectorieslistedinitssys.pathvariable.Ifthemoduleisfound,thenthestatementsinthebodyofthatmodulearerunandthemoduleismadeavailableforyoutouse.Notethattheinitializationisdoneonlythefirsttimethatweimportamodule.
Theargvvariableinthesysmoduleisaccessedusingthedottednotationi.e.sys.argv.Itclearlyindicatesthatthisnameispartofthesysmodule.Anotheradvantageofthisapproachisthatthenamedoesnotclashwithanyargvvariableusedinyourprogram.
Thesys.argvvariableisalistofstrings(listsareexplainedindetailinalaterchapter.Specifically,thesys.argvcontainsthelistofcommandlineargumentsi.e.theargumentspassedtoyourprogramusingthecommandline.
IfyouareusinganIDEtowriteandruntheseprograms,lookforawaytospecifycommandlineargumentstotheprograminthemenus.
Here,whenweexecutepythonmodule_using_sys.pywearearguments,werunthemodulemodule_using_sys.pywiththepythoncommandandtheotherthingsthatfollowareargumentspassedtotheprogram.Pythonstoresthecommandlineargumentsinthesys.argvvariableforustouse.
Remember,thenameofthescriptrunningisalwaysthefirstargumentinthesys.argvlist.So,inthiscasewewillhave'module_using_sys.py'assys.argv[0],'we'assys.argv[1],'are'assys.argv[2]and'arguments'assys.argv[3].NoticethatPythonstartscountingfrom0andnot1.
Thesys.pathcontainsthelistofdirectorynameswheremodulesareimportedfrom.Observethatthefirststringinsys.pathisempty-thisemptystringindicatesthatthecurrentdirectoryisalsopartofthesys.pathwhichissameasthePYTHONPATHenvironmentvariable.Thismeansthatyoucandirectlyimportmoduleslocatedinthecurrentdirectory.Otherwise,youwillhavetoplaceyourmoduleinoneofthedirectorieslistedinsys.path.
Notethatthecurrentdirectoryisthedirectoryfromwhichtheprogramislaunched.Runimportos;print(os.getcwd())tofindoutthecurrentdirectoryofyourprogram.
Byte-compiled.pycfiles
AByteofPython
68Modules
Importingamoduleisarelativelycostlyaffair,soPythondoessometrickstomakeitfaster.Onewayistocreatebyte-compiledfileswiththeextension.pycwhichisanintermediateformthatPythontransformstheprograminto(remembertheintroductionsectiononhowPythonworks?).This.pycfileisusefulwhenyouimportthemodulethenexttimefromadifferentprogram-itwillbemuchfastersinceaportionoftheprocessingrequiredinimportingamoduleisalreadydone.Also,thesebyte-compiledfilesareplatform-independent.
NOTE:These.pycfilesareusuallycreatedinthesamedirectoryasthecorresponding.pyfiles.IfPythondoesnothavepermissiontowritetofilesinthatdirectory,thenthe.pycfileswillnotbecreated.
Thefrom..importstatementIfyouwanttodirectlyimporttheargvvariableintoyourprogram(toavoidtypingthesys.everytimeforit),thenyoucanusethefromsysimportargvstatement.
WARNING:Ingeneral,avoidusingthefrom..importstatement,usetheimportstatementinstead.Thisisbecauseyourprogramwillavoidnameclashesandwillbemorereadable.
Example:
frommathimportsqrt
print("Squarerootof16is",sqrt(16))
Amodule's__name__Everymodulehasanameandstatementsinamodulecanfindoutthenameoftheirmodule.Thisishandyfortheparticularpurposeoffiguringoutwhetherthemoduleisbeingrunstandaloneorbeingimported.Asmentionedpreviously,whenamoduleisimportedforthefirsttime,thecodeitcontainsgetsexecuted.Wecanusethistomakethemodulebehaveindifferentwaysdependingonwhetheritisbeingusedbyitselforbeingimportedfromanothermodule.Thiscanbeachievedusingthe__name__attributeofthemodule.
Example(saveasmodule_using_name.py):
if__name__=='__main__':
print('Thisprogramisbeingrunbyitself')
else:
print('Iambeingimportedfromanothermodule')
AByteofPython
69Modules
Output:
$pythonmodule_using_name.py
Thisprogramisbeingrunbyitself
$python
>>>importmodule_using_name
Iambeingimportedfromanothermodule
>>>
HowItWorks
EveryPythonmodulehasits__name__defined.Ifthisis'__main__',thatimpliesthatthemoduleisbeingrunstandalonebytheuserandwecantakeappropriateactions.
MakingYourOwnModulesCreatingyourownmodulesiseasy,you'vebeendoingitallalong!ThisisbecauseeveryPythonprogramisalsoamodule.Youjusthavetomakesureithasa.pyextension.Thefollowingexampleshouldmakeitclear.
Example(saveasmymodule.py):
defsay_hi():
print('Hi,thisismymodulespeaking.')
__version__='0.1'
Theabovewasasamplemodule.Asyoucansee,thereisnothingparticularlyspecialaboutitcomparedtoourusualPythonprogram.WewillnextseehowtousethismoduleinourotherPythonprograms.
Rememberthatthemoduleshouldbeplacedeitherinthesamedirectoryastheprogramfromwhichweimportit,orinoneofthedirectorieslistedinsys.path.
Anothermodule(saveasmymodule_demo.py):
importmymodule
mymodule.say_hi()
print('Version',mymodule.__version__)
Output:
AByteofPython
70Modules
$pythonmymodule_demo.py
Hi,thisismymodulespeaking.
Version0.1
HowItWorks
Noticethatweusethesamedottednotationtoaccessmembersofthemodule.Pythonmakesgoodreuseofthesamenotationtogivethedistinctive'Pythonic'feeltoitsothatwedon'thavetokeeplearningnewwaystodothings.
Hereisaversionutilisingthefrom..importsyntax(saveasmymodule_demo2.py):
frommymoduleimportsay_hi,__version__
say_hi()
print('Version',__version__)
Theoutputofmymodule_demo2.pyissameastheoutputofmymodule_demo.py.
Noticethatiftherewasalreadya__version__namedeclaredinthemodulethatimportsmymodule,therewouldbeaclash.Thisisalsolikelybecauseitiscommonpracticeforeachmoduletodeclareit'sversionnumberusingthisname.Hence,itisalwaysrecommendedtoprefertheimportstatementeventhoughitmightmakeyourprogramalittlelonger.
Youcouldalsouse:
frommymoduleimport*
Thiswillimportallpublicnamessuchassay_hibutwouldnotimport__version__becauseitstartswithdoubleunderscores.
WARNING:Rememberthatyoushouldavoidusingimport-star,i.e.frommymoduleimport*.
ZenofPython
OneofPython'sguidingprinciplesisthat"ExplicitisbetterthanImplicit".RunimportthisinPythontolearnmore.
Thedirfunction
AByteofPython
71Modules
Youcanusethebuilt-indirfunctiontolisttheidentifiersthatanobjectdefines.Forexample,foramodule,theidentifiersincludethefunctions,classesandvariablesdefinedinthatmodule.
Whenyousupplyamodulenametothedir()function,itreturnsthelistofthenamesdefinedinthatmodule.Whennoargumentisappliedtoit,itreturnsthelistofnamesdefinedinthecurrentmodule.
Example:
$python
>>>importsys
#getnamesofattributesinsysmodule
>>>dir(sys)
['__displayhook__','__doc__',
'argv','builtin_module_names',
'version','version_info']
#onlyfewentriesshownhere
#getnamesofattributesforcurrentmodule
>>>dir()
['__builtins__','__doc__',
'__name__','__package__']
#createanewvariable'a'
>>>a=5
>>>dir()
['__builtins__','__doc__','__name__','__package__','a']
#delete/removeaname
>>>dela
>>>dir()
['__builtins__','__doc__','__name__','__package__']
HowItWorks
First,weseetheusageofdirontheimportedsysmodule.Wecanseethehugelistofattributesthatitcontains.
Next,weusethedirfunctionwithoutpassingparameterstoit.Bydefault,itreturnsthelistofattributesforthecurrentmodule.Noticethatthelistofimportedmodulesisalsopartofthislist.
AByteofPython
72Modules
Inordertoobservethedirinaction,wedefineanewvariableaandassignitavalueandthencheckdirandweobservethatthereisanadditionalvalueinthelistofthesamename.Weremovethevariable/attributeofthecurrentmoduleusingthedelstatementandthechangeisreflectedagainintheoutputofthedirfunction.
Anoteondel-thisstatementisusedtodeleteavariable/nameandafterthestatementhasrun,inthiscasedela,youcannolongeraccessthevariablea-itisasifitneverexistedbeforeatall.
Notethatthedir()functionworksonanyobject.Forexample,rundir(str)fortheattributesofthestr(string)class.
Thereisalsoavars()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
AByteofPython
73Modules
Packagesarejustaconveniencetohierarchicallyorganizemodules.Youwillseemanyinstancesofthisinthestandardlibrary.
SummaryJustlikefunctionsarereusablepartsofprograms,modulesarereusableprograms.Packagesareanotherhierarchytoorganizemodules.ThestandardlibrarythatcomeswithPythonisanexampleofsuchasetofpackagesandmodules.
Wehaveseenhowtousethesemodulesandcreateourownmodules.
Next,wewilllearnaboutsomeinterestingconceptscalleddatastructures.
AByteofPython
74Modules
DataStructuresDatastructuresarebasicallyjustthat-theyarestructureswhichcanholdsomedatatogether.Inotherwords,theyareusedtostoreacollectionofrelateddata.
Therearefourbuilt-indatastructuresinPython-list,tuple,dictionaryandset.Wewillseehowtouseeachofthemandhowtheymakelifeeasierforus.
ListAlistisadatastructurethatholdsanorderedcollectionofitemsi.e.youcanstoreasequenceofitemsinalist.Thisiseasytoimagineifyoucanthinkofashoppinglistwhereyouhavealistofitemstobuy,exceptthatyouprobablyhaveeachitemonaseparatelineinyourshoppinglistwhereasinPythonyouputcommasinbetweenthem.
ThelistofitemsshouldbeenclosedinsquarebracketssothatPythonunderstandsthatyouarespecifyingalist.Onceyouhavecreatedalist,youcanadd,removeorsearchforitemsinthelist.Sincewecanaddandremoveitems,wesaythatalistisamutabledatatypei.e.thistypecanbealtered.
QuickIntroductionToObjectsAndClassesAlthoughI'vebeengenerallydelayingthediscussionofobjectsandclassestillnow,alittleexplanationisneededrightnowsothatyoucanunderstandlistsbetter.Wewillexplorethistopicindetailinalaterchapter.
Alistisanexampleofusageofobjectsandclasses.Whenweuseavariableiandassignavaluetoit,sayinteger5toit,youcanthinkofitascreatinganobject(i.e.instance)iofclass(i.e.type)int.Infact,youcanreadhelp(int)tounderstandthisbetter.
Aclasscanalsohavemethodsi.e.functionsdefinedforusewithrespecttothatclassonly.Youcanusethesepiecesoffunctionalityonlywhenyouhaveanobjectofthatclass.Forexample,Pythonprovidesanappendmethodforthelistclasswhichallowsyoutoaddanitemtotheendofthelist.Forexample,mylist.append('anitem')willaddthatstringtothelistmylist.Notetheuseofdottednotationforaccessingmethodsoftheobjects.
Aclasscanalsohavefieldswhicharenothingbutvariablesdefinedforusewithrespecttothatclassonly.Youcanusethesevariables/namesonlywhenyouhaveanobjectofthatclass.Fieldsarealsoaccessedbythedottednotation,forexample,mylist.field.
AByteofPython
75DataStructures
Example(saveasds_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)
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
Thevariableshoplistisashoppinglistforsomeonewhoisgoingtothemarket.Inshoplist,weonlystorestringsofthenamesoftheitemstobuybutyoucanaddanykindofobjecttoalistincludingnumbersandevenotherlists.
Wehavealsousedthefor..inlooptoiteratethroughtheitemsofthelist.Bynow,youmusthaverealisedthatalistisalsoasequence.Thespecialityofsequenceswillbediscussedinalatersection.
AByteofPython
76DataStructures
Noticetheuseoftheendparameterinthecalltoprintfunctiontoindicatethatwewanttoendtheoutputwithaspaceinsteadoftheusuallinebreak.
Next,weaddanitemtothelistusingtheappendmethodofthelistobject,asalreadydiscussedbefore.Then,wecheckthattheitemhasbeenindeedaddedtothelistbyprintingthecontentsofthelistbysimplypassingthelisttotheprintfunctionwhichprintsitneatly.
Then,wesortthelistbyusingthesortmethodofthelist.Itisimportanttounderstandthatthismethodaffectsthelistitselfanddoesnotreturnamodifiedlist-thisisdifferentfromthewaystringswork.Thisiswhatwemeanbysayingthatlistsaremutableandthatstringsareimmutable.
Next,whenwefinishbuyinganiteminthemarket,wewanttoremoveitfromthelist.Weachievethisbyusingthedelstatement.Here,wementionwhichitemofthelistwewanttoremoveandthedelstatementremovesitfromthelistforus.Wespecifythatwewanttoremovethefirstitemfromthelistandhenceweusedelshoplist[0](rememberthatPythonstartscountingfrom0).
Ifyouwanttoknowallthemethodsdefinedbythelistobject,seehelp(list)fordetails.
TupleTuplesareusedtoholdtogethermultipleobjects.Thinkofthemassimilartolists,butwithouttheextensivefunctionalitythatthelistclassgivesyou.Onemajorfeatureoftuplesisthattheyareimmutablelikestringsi.e.youcannotmodifytuples.
Tuplesaredefinedbyspecifyingitemsseparatedbycommaswithinanoptionalpairofparentheses.
Tuplesareusuallyusedincaseswhereastatementorauser-definedfunctioncansafelyassumethatthecollectionofvaluesi.e.thetupleofvaluesusedwillnotchange.
Example(saveasds_using_tuple.py):
AByteofPython
77DataStructures
#Iwouldrecommendalwaysusingparentheses
#toindicatestartandendoftuple
#eventhoughparenthesesareoptional.
#Explicitisbetterthanimplicit.
zoo=('python','elephant','penguin')
print('Numberofanimalsinthezoois',len(zoo))
new_zoo='monkey','camel',zoo
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
Thevariablezooreferstoatupleofitems.Weseethatthelenfunctioncanbeusedtogetthelengthofthetuple.Thisalsoindicatesthatatupleisasequenceaswell.
Wearenowshiftingtheseanimalstoanewzoosincetheoldzooisbeingclosed.Therefore,thenew_zootuplecontainssomeanimalswhicharealreadytherealongwiththeanimalsbroughtoverfromtheoldzoo.Backtoreality,notethatatuplewithinatupledoesnotloseitsidentity.
Wecanaccesstheitemsinthetuplebyspecifyingtheitem'spositionwithinapairofsquarebracketsjustlikewedidforlists.Thisiscalledtheindexingoperator.Weaccessthethirditeminnew_zoobyspecifyingnew_zoo[2]andweaccessthethirditemwithinthethirditeminthenew_zootuplebyspecifyingnew_zoo[2][2].Thisisprettysimpleonceyou'veunderstoodtheidiom.
AByteofPython
78DataStructures
Tuplewith0or1items
Anemptytupleisconstructedbyanemptypairofparenthesessuchasmyempty=().However,atuplewithasingleitemisnotsosimple.Youhavetospecifyitusingacommafollowingthefirst(andonly)itemsothatPythoncandifferentiatebetweenatupleandapairofparenthesessurroundingtheobjectinanexpressioni.e.youhavetospecifysingleton=(2,)ifyoumeanyouwantatuplecontainingtheitem2.
NoteforPerlprogrammers
Alistwithinalistdoesnotloseitsidentityi.e.listsarenotflattenedasinPerl.Thesameappliestoatuplewithinatuple,oratuplewithinalist,oralistwithinatuple,etc.AsfarasPythonisconcerned,theyarejustobjectsstoredusinganotherobject,that'sall.
DictionaryAdictionaryislikeanaddress-bookwhereyoucanfindtheaddressorcontactdetailsofapersonbyknowingonlyhis/hernamei.e.weassociatekeys(name)withvalues(details).Notethatthekeymustbeuniquejustlikeyoucannotfindoutthecorrectinformationifyouhavetwopersonswiththeexactsamename.
Notethatyoucanuseonlyimmutableobjects(likestrings)forthekeysofadictionarybutyoucanuseeitherimmutableormutableobjectsforthevaluesofthedictionary.Thisbasicallytranslatestosaythatyoushoulduseonlysimpleobjectsforkeys.
Pairsofkeysandvaluesarespecifiedinadictionarybyusingthenotationd={key1:value1,key2:value2}.Noticethatthekey-valuepairsareseparatedbyacolonandthepairsareseparatedthemselvesbycommasandallthisisenclosedinapairofcurlybraces.
Rememberthatkey-valuepairsinadictionaryarenotorderedinanymanner.Ifyouwantaparticularorder,thenyouwillhavetosortthemyourselfbeforeusingit.
Thedictionariesthatyouwillbeusingareinstances/objectsofthedictclass.
Example(saveasds_using_dict.py):
AByteofPython
79DataStructures
#'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
Wecreatethedictionaryabusingthenotationalreadydiscussed.Wethenaccesskey-valuepairsbyspecifyingthekeyusingtheindexingoperatorasdiscussedinthecontextoflistsandtuples.Observethesimplesyntax.
Wecandeletekey-valuepairsusingouroldfriend-thedelstatement.Wesimplyspecifythedictionaryandtheindexingoperatorforthekeytoberemovedandpassittothedelstatement.Thereisnoneedtoknowthevaluecorrespondingtothekeyforthisoperation.
AByteofPython
80DataStructures
Next,weaccesseachkey-valuepairofthedictionaryusingtheitemsmethodofthedictionarywhichreturnsalistoftupleswhereeachtuplecontainsapairofitems-thekeyfollowedbythevalue.Weretrievethispairandassignittothevariablesnameandaddresscorrespondinglyforeachpairusingthefor..inloopandthenprintthesevaluesinthefor-block.
Wecanaddnewkey-valuepairsbysimplyusingtheindexingoperatortoaccessakeyandassignthatvalue,aswehavedoneforGuidointheabovecase.
Wecancheckifakey-valuepairexistsusingtheinoperator.
Forthelistofmethodsofthedictclass,seehelp(dict).
KeywordArgumentsandDictionaries
Ifyouhaveusedkeywordargumentsinyourfunctions,youhavealreadyuseddictionaries!Justthinkaboutit-thekey-valuepairisspecifiedbyyouintheparameterlistofthefunctiondefinitionandwhenyouaccessvariableswithinyourfunction,itisjustakeyaccessofadictionary(whichiscalledthesymboltableincompilerdesignterminology).
SequenceLists,tuplesandstringsareexamplesofsequences,butwhataresequencesandwhatissospecialaboutthem?
Themajorfeaturesaremembershiptests,(i.e.theinandnotinexpressions)andindexingoperations,whichallowustofetchaparticulariteminthesequencedirectly.
Thethreetypesofsequencesmentionedabove-lists,tuplesandstrings,alsohaveaslicingoperationwhichallowsustoretrieveasliceofthesequencei.e.apartofthesequence.
Example(saveasds_seq.py):
AByteofPython
81DataStructures
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']
Itemstarttoendis['apple','mango','carrot','banana']
characters1to3iswa
characters2toendisaroop
characters1to-1iswaroo
charactersstarttoendisswaroop
HowItWorks
First,weseehowtouseindexestogetindividualitemsofasequence.Thisisalsoreferredtoasthesubscriptionoperation.Wheneveryouspecifyanumbertoasequencewithinsquarebracketsasshownabove,Pythonwillfetchyoutheitemcorrespondingtothat
AByteofPython
82DataStructures
positioninthesequence.RememberthatPythonstartscountingnumbersfrom0.Hence,shoplist[0]fetchesthefirstitemandshoplist[3]fetchesthefourthitemintheshoplistsequence.
Theindexcanalsobeanegativenumber,inwhichcase,thepositioniscalculatedfromtheendofthesequence.Therefore,shoplist[-1]referstothelastiteminthesequenceandshoplist[-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.
AByteofPython
83DataStructures
TryvariouscombinationsofsuchslicespecificationsusingthePythoninterpreterinteractivelyi.e.thepromptsothatyoucanseetheresultsimmediately.Thegreatthingaboutsequencesisthatyoucanaccesstuples,listsandstringsallinthesameway!
SetSetsareunorderedcollectionsofsimpleobjects.Theseareusedwhentheexistenceofanobjectinacollectionismoreimportantthantheorderorhowmanytimesitoccurs.
Usingsets,youcantestformembership,whetheritisasubsetofanotherset,findtheintersectionbetweentwosets,andsoon.
>>>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
Theexampleisprettymuchself-explanatorybecauseitinvolvesbasicsettheorymathematicstaughtinschool.
ReferencesWhenyoucreateanobjectandassignittoavariable,thevariableonlyreferstotheobjectanddoesnotrepresenttheobjectitself!Thatis,thevariablenamepointstothatpartofyourcomputer'smemorywheretheobjectisstored.Thisiscalledbindingthenametotheobject.
Generally,youdon'tneedtobeworriedaboutthis,butthereisasubtleeffectduetoreferenceswhichyouneedtobeawareof:
Example(saveasds_reference.py):
AByteofPython
84DataStructures
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']
HowItWorks
Mostoftheexplanationisavailableinthecomments.
Rememberthatifyouwanttomakeacopyofalistorsuchkindsofsequencesorcomplexobjects(notsimpleobjectssuchasintegers),thenyouhavetousetheslicingoperationtomakeacopy.Ifyoujustassignthevariablenametoanothername,bothofthemwill''refer''tothesameobjectandthiscouldbetroubleifyouarenotcareful.
NoteforPerlprogrammers
Rememberthatanassignmentstatementforlistsdoesnotcreateacopy.Youhavetouseslicingoperationtomakeacopyofthesequence.
AByteofPython
85DataStructures
MoreAboutStringsWehavealreadydiscussedstringsindetailearlier.Whatmorecantherebetoknow?Well,didyouknowthatstringsarealsoobjectsandhavemethodswhichdoeverythingfromcheckingpartofastringtostrippingspaces!
Thestringsthatyouuseinprogramareallobjectsoftheclassstr.Someusefulmethodsofthisclassaredemonstratedinthenextexample.Foracompletelistofsuchmethods,seehelp(str).
Example(saveasds_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.Thestartswithmethodisusedtofindoutwhetherthestringstartswiththegivenstring.Theinoperatorisusedtocheckifagivenstringisapartofthestring.
Thefindmethodisusedtolocatethepositionofthegivensubstringwithinthestring;findreturns-1ifitisunsuccessfulinfindingthesubstring.Thestrclassalsohasaneatmethodtojointheitemsofasequencewiththestringactingasadelimiterbetweeneachitemofthesequenceandreturnsabiggerstringgeneratedfromthis.
AByteofPython
86DataStructures
SummaryWehaveexploredthevariousbuilt-indatastructuresofPythonindetail.Thesedatastructureswillbeessentialforwritingprogramsofreasonablesize.
NowthatwehavealotofthebasicsofPythoninplace,wewillnextseehowtodesignandwriteareal-worldPythonprogram.
AByteofPython
87DataStructures
ProblemSolvingWehaveexploredvariouspartsofthePythonlanguageandnowwewilltakealookathowallthesepartsfittogether,bydesigningandwritingaprogramwhichdoessomethinguseful.TheideaistolearnhowtowriteaPythonscriptonyourown.
TheProblemTheproblemwewanttosolveis:
Iwantaprogramwhichcreatesabackupofallmyimportantfiles.
Although,thisisasimpleproblem,thereisnotenoughinformationforustogetstartedwiththesolution.Alittlemoreanalysisisrequired.Forexample,howdowespecifywhichfilesaretobebackedup?Howaretheystored?Wherearetheystored?
Afteranalyzingtheproblemproperly,wedesignourprogram.Wemakealistofthingsabouthowourprogramshouldwork.Inthiscase,IhavecreatedthefollowinglistonhowIwantittowork.Ifyoudothedesign,youmaynotcomeupwiththesamekindofanalysissinceeverypersonhastheirownwayofdoingthings,sothatisperfectlyokay.
Thefilesanddirectoriestobebackeduparespecifiedinalist.Thebackupmustbestoredinamainbackupdirectory.Thefilesarebackedupintoazipfile.Thenameoftheziparchiveisthecurrentdateandtime.WeusethestandardzipcommandavailablebydefaultinanystandardGNU/LinuxorUnixdistribution.Notethatyoucanuseanyarchivingcommandyouwantaslongasithasacommandlineinterface.
ForWindowsusers
WindowsuserscaninstallthezipcommandfromtheGnuWin32projectpageandaddC:\ProgramFiles\GnuWin32\bintoyoursystemPATHenvironmentvariable,similartowhatwedidforrecognizingthepythoncommanditself.
TheSolutionAsthedesignofourprogramisnowreasonablystable,wecanwritethecodewhichisanimplementationofoursolution.
AByteofPython
88ProblemSolving
Saveasbackup_ver1.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
#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:
AByteofPython
89ProblemSolving
$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,copythelineprintedaftertheZipcommandislineintheoutput,pasteitintheshell(onGNU/LinuxandMacOSX)/cmd(onWindows),seewhattheerrorisandtrytofixit.Alsocheckthezipcommandmanualonwhatcouldbewrong.Ifthiscommandsucceeds,thentheproblemmightbeinthePythonprogramitself,socheckifitexactlymatchestheprogramwrittenabove.
HowItWorks
Youwillnoticehowwehaveconvertedourdesignintocodeinastep-by-stepmanner.
Wemakeuseoftheosandtimemodulesbyfirstimportingthem.Then,wespecifythefilesanddirectoriestobebackedupinthesourcelist.Thetargetdirectoryiswherewestoreallthebackupfilesandthisisspecifiedinthetarget_dirvariable.Thenameoftheziparchivethatwearegoingtocreateisthecurrentdateandtimewhichwegenerateusingthetime.strftime()function.Itwillalsohavethe.zipextensionandwillbestoredinthetarget_dirdirectory.
Noticetheuseoftheos.sepvariable-thisgivesthedirectoryseparatoraccordingtoyouroperatingsystemi.e.itwillbe'/'inGNU/LinuxandUnix,itwillbe'\\'inWindowsand':'inMacOS.Usingos.sepinsteadofthesecharactersdirectlywillmakeourprogramportableandworkacrossallofthesesystems.
Thetime.strftime()functiontakesaspecificationsuchastheonewehaveusedintheaboveprogram.The%Yspecificationwillbereplacedbytheyearwiththecentury.The%mspecificationwillbereplacedbythemonthasadecimalnumberbetween01and12andsoon.ThecompletelistofsuchspecificationscanbefoundinthePythonReferenceManual.
Wecreatethenameofthetargetzipfileusingtheadditionoperatorwhichconcatenatesthestringsi.e.itjoinsthetwostringstogetherandreturnsanewone.Then,wecreateastringzip_commandwhichcontainsthecommandthatwearegoingtoexecute.Youcancheckif
AByteofPython
90ProblemSolving
thiscommandworksbyrunningitintheshell(GNU/LinuxterminalorDOSprompt).
Thezipcommandthatweareusinghassomeoptionsandparameterspassed.The-roptionspecifiesthatthezipcommandshouldworkrecursivelyfordirectoriesi.e.itshouldincludeallthesubdirectoriesandfiles.Thetwooptionsarecombinedandspecifiedinashortcutas-qr.Theoptionsarefollowedbythenameoftheziparchivetocreatefollowedbythelistoffilesanddirectoriestobackup.Weconvertthesourcelistintoastringusingthejoinmethodofstringswhichwehavealreadyseenhowtouse.
Then,wefinallyrunthecommandusingtheos.systemfunctionwhichrunsthecommandasifitwasrunfromthesystemi.e.intheshell-itreturns0ifthecommandwassuccessfully,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.
SecondVersionThefirstversionofourscriptworks.However,wecanmakesomerefinementstoitsothatitcanworkbetteronadailybasis.Thisiscalledthemaintenancephaseofthesoftware.
OneoftherefinementsIfeltwasusefulisabetterfile-namingmechanism-usingthetimeasthenameofthefilewithinadirectorywiththecurrentdateasadirectorywithinthemainbackupdirectory.Thefirstadvantageisthatyourbackupsarestoredinahierarchicalmannerandthereforeitismucheasiertomanage.Thesecondadvantageisthatthe
AByteofPython
91ProblemSolving
filenamesaremuchshorter.Thethirdadvantageisthatseparatedirectorieswillhelpyoucheckifyouhavemadeabackupforeachdaysincethedirectorywouldbecreatedonlyifyouhavemadeabackupforthatday.
Saveasbackup_ver2.py:
AByteofPython
92ProblemSolving
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')
#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')
AByteofPython
93ProblemSolving
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.Thechangesarethatwecheckifthereisadirectorywiththecurrentdayasitsnameinsidethemainbackupdirectoryusingtheos.path.existsfunction.Ifitdoesn'texist,wecreateitusingtheos.mkdirfunction.
ThirdVersionThesecondversionworksfinewhenIdomanybackups,butwhentherearelotsofbackups,Iamfindingithardtodifferentiatewhatthebackupswerefor!Forexample,Imighthavemadesomemajorchangestoaprogramorpresentation,thenIwanttoassociatewhatthosechangesarewiththenameoftheziparchive.Thiscanbeeasilyachievedbyattachingauser-suppliedcommenttothenameoftheziparchive.
WARNING:Thefollowingprogramdoesnotwork,sodonotbealarmed,pleasefollowalongbecausethere'salessoninhere.
Saveasbackup_ver3.py:
importos
importtime
#1.Thefilesanddirectoriestobebackedupare
#specifiedinalist.
#ExampleonWindows:
#source=['"C:\\MyDocuments"','C:\\Code']
#ExampleonMacOSXandLinux:
source=['/Users/swa/notes']
#Noticewehadtousedoublequotesinsidethestring
#fornameswithspacesinit.
#2.Thebackupmustbestoredina
#mainbackupdirectory
AByteofPython
94ProblemSolving
#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:
AByteofPython
95ProblemSolving
$pythonbackup_ver3.py
File"backup_ver3.py",line39
target=today+os.sep+now+'_'+
^
SyntaxError:invalidsyntax
HowThis(doesnot)Work
Thisprogramdoesnotwork!PythonsaysthereisasyntaxerrorwhichmeansthatthescriptdoesnotsatisfythestructurethatPythonexpectstosee.WhenweobservetheerrorgivenbyPython,italsotellsustheplacewhereitdetectedtheerroraswell.Sowestartdebuggingourprogramfromthatline.
Oncarefulobservation,weseethatthesinglelogicallinehasbeensplitintotwophysicallinesbutwehavenotspecifiedthatthesetwophysicallinesbelongtogether.Basically,Pythonhasfoundtheadditionoperator(+)withoutanyoperandinthatlogicallineandhenceitdoesn'tknowhowtocontinue.Rememberthatwecanspecifythatthelogicallinecontinuesinthenextphysicallinebytheuseofabackslashattheendofthephysicalline.So,wemakethiscorrectiontoourprogram.Thiscorrectionoftheprogramwhenwefinderrorsiscalledbugfixing.
FourthVersionSaveasbackup_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
AByteofPython
96ProblemSolving
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_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
AByteofPython
97ProblemSolving
HowItWorks
Thisprogramnowworks!Letusgothroughtheactualenhancementsthatwehadmadeinversion3.Wetakeintheuser'scommentsusingtheinputfunctionandthencheckiftheuseractuallyenteredsomethingbyfindingoutthelengthoftheinputusingthelenfunction.Iftheuserhasjustpressedenterwithoutenteringanything(maybeitwasjustaroutinebackupornospecialchangesweremade),thenweproceedaswehavedonebefore.
However,ifacommentwassupplied,thenthisisattachedtothenameoftheziparchivejustbeforethe.zipextension.Noticethatwearereplacingspacesinthecommentwithunderscores-thisisbecausemanagingfilenameswithoutspacesismucheasier.
MoreRefinementsThefourthversionisasatisfactorilyworkingscriptformostusers,butthereisalwaysroomforimprovement.Forexample,youcanincludeaverbositylevelfortheprogramwhereyoucanspecifya-voptiontomakeyourprogrambecomemoretalkativeora-qtomakeitquiet.
Anotherpossibleenhancementwouldbetoallowextrafilesanddirectoriestobepassedtothescriptatthecommandline.Wecangetthesenamesfromthesys.argvlistandwecanaddthemtooursourcelistusingtheextendmethodprovidedbythelistclass.
Themostimportantrefinementwouldbetonotusetheos.systemwayofcreatingarchivesandinsteadusingthezipfileortarfilebuilt-inmodulestocreatethesearchives.Theyarepartofthestandardlibraryandavailablealreadyforyoutousewithoutexternaldependenciesonthezipprogramtobeavailableonyourcomputer.
However,Ihavebeenusingtheos.systemwayofcreatingabackupintheaboveexamplespurelyforpedagogicalpurposes,sothattheexampleissimpleenoughtobeunderstoodbyeverybodybutrealenoughtobeuseful.
Canyoutrywritingthefifthversionthatusesthezipfilemoduleinsteadoftheos.systemcall?
TheSoftwareDevelopmentProcessWehavenowgonethroughthevariousphasesintheprocessofwritingasoftware.Thesephasescanbesummarisedasfollows:
1. What(Analysis)
AByteofPython
98ProblemSolving
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
SummaryWehaveseenhowtocreateourownPythonprograms/scriptsandthevariousstagesinvolvedinwritingsuchprograms.YoumayfinditusefultocreateyourownprogramjustlikewedidinthischaptersothatyoubecomecomfortablewithPythonaswellasproblem-solving.
Next,wewilldiscussobject-orientedprogramming.
AByteofPython
99ProblemSolving
ObjectOrientedProgrammingInalltheprogramswewrotetillnow,wehavedesignedourprogramaroundfunctionsi.e.blocksofstatementswhichmanipulatedata.Thisiscalledtheprocedure-orientedwayofprogramming.Thereisanotherwayoforganizingyourprogramwhichistocombinedataandfunctionalityandwrapitinsidesomethingcalledanobject.Thisiscalledtheobjectorientedprogrammingparadigm.Mostofthetimeyoucanuseproceduralprogramming,butwhenwritinglargeprogramsorhaveaproblemthatisbettersuitedtothismethod,youcanuseobjectorientedprogrammingtechniques.
Classesandobjectsarethetwomainaspectsofobjectorientedprogramming.Aclasscreatesanewtypewhereobjectsareinstancesoftheclass.Ananalogyisthatyoucanhavevariablesoftypeintwhichtranslatestosayingthatvariablesthatstoreintegersarevariableswhichareinstances(objects)oftheintclass.
NoteforStaticLanguageProgrammers
Notethatevenintegersaretreatedasobjects(oftheintclass).ThisisunlikeC++andJava(beforeversion1.5)whereintegersareprimitivenativetypes.
Seehelp(int)formoredetailsontheclass.
C#andJava1.5programmerswillfindthissimilartotheboxingandunboxingconcept.
Objectscanstoredatausingordinaryvariablesthatbelongtotheobject.Variablesthatbelongtoanobjectorclassarereferredtoasfields.Objectscanalsohavefunctionalitybyusingfunctionsthatbelongtoaclass.Suchfunctionsarecalledmethodsoftheclass.Thisterminologyisimportantbecauseithelpsustodifferentiatebetweenfunctionsandvariableswhichareindependentandthosewhichbelongtoaclassorobject.Collectively,thefieldsandmethodscanbereferredtoastheattributesofthatclass.
Fieldsareoftwotypes-theycanbelongtoeachinstance/objectoftheclassortheycanbelongtotheclassitself.Theyarecalledinstancevariablesandclassvariablesrespectively.
Aclassiscreatedusingtheclasskeyword.Thefieldsandmethodsoftheclassarelistedinanindentedblock.
Theself
AByteofPython
100ObjectOrientedProgramming
Classmethodshaveonlyonespecificdifferencefromordinaryfunctions-theymusthaveanextrafirstnamethathastobeaddedtothebeginningoftheparameterlist,butyoudonotgiveavalueforthisparameterwhenyoucallthemethod,Pythonwillprovideit.Thisparticularvariablereferstotheobjectitself,andbyconvention,itisgiventhenameself.
Although,youcangiveanynameforthisparameter,itisstronglyrecommendedthatyouusethenameself-anyothernameisdefinitelyfrownedupon.Therearemanyadvantagestousingastandardname-anyreaderofyourprogramwillimmediatelyrecognizeitandevenspecializedIDEs(IntegratedDevelopmentEnvironments)canhelpyouifyouuseself.
NoteforC++/Java/C#Programmers
TheselfinPythonisequivalenttothethispointerinC++andthethisreferenceinJavaandC#.
YoumustbewonderinghowPythongivesthevalueforselfandwhyyoudon'tneedtogiveavalueforit.Anexamplewillmakethisclear.SayyouhaveaclasscalledMyClassandaninstanceofthisclasscalledmyobject.Whenyoucallamethodofthisobjectasmyobject.method(arg1,arg2),thisisautomaticallyconvertedbyPythonintoMyClass.method(myobject,arg1,arg2)-thisisallthespecialselfisabout.
Thisalsomeansthatifyouhaveamethodwhichtakesnoarguments,thenyoustillhavetohaveoneargument-theself.
ClassesThesimplestclasspossibleisshowninthefollowingexample(saveasoop_simplestclass.py).
classPerson:
pass#Anemptyblock
p=Person()
print(p)
Output:
$pythonoop_simplestclass.py
HowItWorks
AByteofPython
101ObjectOrientedProgramming
Wecreateanewclassusingtheclassstatementandthenameoftheclass.Thisisfollowedbyanindentedblockofstatementswhichformthebodyoftheclass.Inthiscase,wehaveanemptyblockwhichisindicatedusingthepassstatement.
Next,wecreateanobject/instanceofthisclassusingthenameoftheclassfollowedbyapairofparentheses.(Wewilllearn<>inthenextsection).Forourverification,weconfirmthetypeofthevariablebysimplyprintingit.IttellsusthatwehaveaninstanceofthePersonclassinthe__main__module.
Noticethattheaddressofthecomputermemorywhereyourobjectisstoredisalsoprinted.TheaddresswillhaveadifferentvalueonyourcomputersincePythoncanstoretheobjectwhereveritfindsspace.
MethodsWehavealreadydiscussedthatclasses/objectscanhavemethodsjustlikefunctionsexceptthatwehaveanextraselfvariable.Wewillnowseeanexample(saveasoop_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
Hereweseetheselfinaction.Noticethatthesay_himethodtakesnoparametersbutstillhastheselfinthefunctiondefinition.
The__init__methodTherearemanymethodnameswhichhavespecialsignificanceinPythonclasses.Wewillseethesignificanceofthe__init__methodnow.
AByteofPython
102ObjectOrientedProgramming
The__init__methodisrunassoonasanobjectofaclassisinstantiated.Themethodisusefultodoanyinitializationyouwanttodowithyourobject.Noticethedoubleunderscoresbothatthebeginningandattheendofthename.
Example(saveasoop_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__methodastakingaparametername(alongwiththeusualself).Here,wejustcreateanewfieldalsocalledname.Noticethesearetwodifferentvariableseventhoughtheyarebothcalled'name'.Thereisnoproblembecausethedottednotationself.namemeansthatthereissomethingcalled"name"thatispartoftheobjectcalled"self"andtheothernameisalocalvariable.Sinceweexplicitlyindicatewhichnamewearereferringto,thereisnoconfusion.
Mostimportantly,noticethatwedonotexplicitlycallthe__init__methodbutpasstheargumentsintheparenthesesfollowingtheclassnamewhencreatinganewinstanceoftheclass.Thisisthespecialsignificanceofthismethod.
Now,weareabletousetheself.namefieldinourmethodswhichisdemonstratedinthesay_himethod.
ClassAndObjectVariablesWehavealreadydiscussedthefunctionalitypartofclassesandobjects(i.e.methods),nowletuslearnaboutthedatapart.Thedatapart,i.e.fields,arenothingbutordinaryvariablesthatareboundtothenamespacesoftheclassesandobjects.Thismeansthatthesenames
AByteofPython
103ObjectOrientedProgramming
arevalidwithinthecontextoftheseclassesandobjectsonly.That'swhytheyarecallednamespaces.
Therearetwotypesoffields-classvariablesandobjectvariableswhichareclassifieddependingonwhethertheclassortheobjectownsthevariablesrespectively.
Classvariablesareshared-theycanbeaccessedbyallinstancesofthatclass.Thereisonlyonecopyoftheclassvariableandwhenanyoneobjectmakesachangetoaclassvariable,thatchangewillbeseenbyalltheotherinstances.
Objectvariablesareownedbyeachindividualobject/instanceoftheclass.Inthiscase,eachobjecthasitsowncopyofthefieldi.e.theyarenotsharedandarenotrelatedinanywaytothefieldbythesamenameinadifferentinstance.Anexamplewillmakethiseasytounderstand(saveasoop_objvar.py):
classRobot:
"""Representsarobot,withaname."""
#Aclassvariable,countingthenumberofrobots
population=0
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):
AByteofPython
104ObjectOrientedProgramming
"""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.
Wehave0robots.
HowItWorks
Thisisalongexamplebuthelpsdemonstratethenatureofclassandobjectvariables.Here,populationbelongstotheRobotclassandhenceisaclassvariable.Thenamevariablebelongstotheobject(itisassignedusingself)andhenceisanobjectvariable.
Thus,werefertothepopulationclassvariableasRobot.populationandnotasself.population.Werefertotheobjectvariablenameusingself.namenotationinthemethodsofthatobject.Rememberthissimpledifferencebetweenclassandobject
AByteofPython
105ObjectOrientedProgramming
variables.Alsonotethatanobjectvariablewiththesamenameasaclassvariablewillhidetheclassvariable!
InsteadofRobot.population,wecouldhavealsousedself.__class__.populationbecauseeveryobjectreferstoit'sclassviatheself.__class__attribute.
Thehow_manyisactuallyamethodthatbelongstotheclassandnottotheobject.Thismeanswecandefineitaseitheraclassmethodorastaticmethoddependingonwhetherweneedtoknowwhichclasswearepartof.Sincewerefertoaclassvariable,let'suseclassmethod.
Wehavemarkedthehow_manymethodasaclassmethodusingadecorator.
Decoratorscanbeimaginedtobeashortcuttocallingawrapperfunction,soapplyingthe@classmethoddecoratorissameascalling:
how_many=classmethod(how_many)
Observethatthe__init__methodisusedtoinitializetheRobotinstancewithaname.Inthismethod,weincreasethepopulationcountby1sincewehaveonemorerobotbeingadded.Alsoobservethatthevaluesofself.nameisspecifictoeachobjectwhichindicatesthenatureofobjectvariables.
Remember,thatyoumustrefertothevariablesandmethodsofthesameobjectusingtheselfonly.Thisiscalledanattributereference.
Inthisprogram,wealsoseetheuseofdocstringsforclassesaswellasmethods.WecanaccesstheclassdocstringatruntimeusingRobot.__doc__andthemethoddocstringasRobot.say_hi.__doc__
Inthediemethod,wesimplydecreasetheRobot.populationcountby1.
Allclassmembersarepublic.Oneexception:Ifyouusedatamemberswithnamesusingthedoubleunderscoreprefixsuchas__privatevar,Pythonusesname-manglingtoeffectivelymakeitaprivatevariable.
Thus,theconventionfollowedisthatanyvariablethatistobeusedonlywithintheclassorobjectshouldbeginwithanunderscoreandallothernamesarepublicandcanbeusedbyotherclasses/objects.RememberthatthisisonlyaconventionandisnotenforcedbyPython(exceptforthedoubleunderscoreprefix).
NoteforC++/Java/C#Programmers
Allclassmembers(includingthedatamembers)arepublicandallthemethodsarevirtualinPython.
AByteofPython
106ObjectOrientedProgramming
InheritanceOneofthemajorbenefitsofobjectorientedprogrammingisreuseofcodeandoneofthewaysthisisachievedisthroughtheinheritancemechanism.Inheritancecanbebestimaginedasimplementingatypeandsubtyperelationshipbetweenclasses.
Supposeyouwanttowriteaprogramwhichhastokeeptrackoftheteachersandstudentsinacollege.Theyhavesomecommoncharacteristicssuchasname,ageandaddress.Theyalsohavespecificcharacteristicssuchassalary,coursesandleavesforteachersand,marksandfeesforstudents.
Youcancreatetwoindependentclassesforeachtypeandprocessthembutaddinganewcommoncharacteristicwouldmeanaddingtobothoftheseindependentclasses.Thisquicklybecomesunwieldy.
AbetterwaywouldbetocreateacommonclasscalledSchoolMemberandthenhavetheteacherandstudentclassesinheritfromthisclassi.e.theywillbecomesub-typesofthistype(class)andthenwecanaddspecificcharacteristicstothesesub-types.
Therearemanyadvantagestothisapproach.Ifweadd/changeanyfunctionalityinSchoolMember,thisisautomaticallyreflectedinthesubtypesaswell.Forexample,youcanaddanewIDcardfieldforbothteachersandstudentsbysimplyaddingittotheSchoolMemberclass.However,changesinthesubtypesdonotaffectothersubtypes.AnotheradvantageisthatifyoucanrefertoateacherorstudentobjectasaSchoolMemberobjectwhichcouldbeusefulinsomesituationssuchascountingofthenumberofschoolmembers.Thisiscalledpolymorphismwhereasub-typecanbesubstitutedinanysituationwhereaparenttypeisexpectedi.e.theobjectcanbetreatedasaninstanceoftheparentclass.
Alsoobservethatwereusethecodeoftheparentclassandwedonotneedtorepeatitinthedifferentclassesaswewouldhavehadtoincasewehadusedindependentclasses.
TheSchoolMemberclassinthissituationisknownasthebaseclassorthesuperclass.TheTeacherandStudentclassesarecalledthederivedclassesorsubclasses.
Wewillnowseethisexampleasaprogram(saveasoop_subclass.py):
AByteofPython
107ObjectOrientedProgramming
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
member.tell()
Output:
AByteofPython
108ObjectOrientedProgramming
$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.Next,weobservethatthe__init__methodofthebaseclassisexplicitlycalledusingtheselfvariablesothatwecaninitializethebaseclasspartoftheobject.Thisisveryimportanttoremember-Pythondoesnotautomaticallycalltheconstructorofthebaseclass,youhavetoexplicitlycallityourself.
Wealsoobservethatwecancallmethodsofthebaseclassbyprefixingtheclassnametothemethodcallandthenpassintheselfvariablealongwithanyarguments.
NoticethatwecantreatinstancesofTeacherorStudentasjustinstancesoftheSchoolMemberwhenweusethetellmethodoftheSchoolMemberclass.
Also,observethatthetellmethodofthesubtypeiscalledandnotthetellmethodoftheSchoolMemberclass.OnewaytounderstandthisisthatPythonalwaysstartslookingformethodsintheactualtype,whichinthiscaseitdoes.Ifitcouldnotfindthemethod,itstartslookingatthemethodsbelongingtoitsbaseclassesonebyoneintheordertheyarespecifiedinthetupleintheclassdefinition.
Anoteonterminology-ifmorethanoneclassislistedintheinheritancetuple,thenitiscalledmultipleinheritance.
Theendparameterisusedintheprintfunctioninthesuperclass'stell()methodtoprintalineandallowthenextprinttocontinueonthesameline.Thisisatricktomakeprintnotprinta\n(newline)symbolattheendoftheprinting.
SummaryWehavenowexploredthevariousaspectsofclassesandobjectsaswellasthevariousterminologiesassociatedwithit.Wehavealsoseenthebenefitsandpitfallsofobject-orientedprogramming.Pythonishighlyobject-orientedandunderstandingtheseconceptscarefullywillhelpyoualotinthelongrun.
Next,wewilllearnhowtodealwithinput/outputandhowtoaccessfilesinPython.
AByteofPython
109ObjectOrientedProgramming
AByteofPython
110ObjectOrientedProgramming
InputandOutputTherewillbesituationswhereyourprogramhastointeractwiththeuser.Forexample,youwouldwanttotakeinputfromtheuserandthenprintsomeresultsback.Wecanachievethisusingtheinput()functionandprintfunctionrespectively.
Foroutput,wecanalsousethevariousmethodsofthestr(string)class.Forexample,youcanusetherjustmethodtogetastringwhichisrightjustifiedtoaspecifiedwidth.Seehelp(str)formoredetails.
Anothercommontypeofinput/outputisdealingwithfiles.Theabilitytocreate,readandwritefilesisessentialtomanyprogramsandwewillexplorethisaspectinthischapter.
InputfromuserSavethisprogramasio_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:
AByteofPython
111InputandOutput
$python3io_input.py
Entertext:sir
No,itisnotapalindrome
$python3io_input.py
Entertext:madam
Yes,itisapalindrome
$python3io_input.py
Entertext:racecar
Yes,itisapalindrome
HowItWorks
Weusetheslicingfeaturetoreversethetext.We'vealreadyseenhowwecanmakeslicesfromsequencesusingtheseq[a:b]codestartingfrompositionatopositionb.Wecanalsoprovideathirdargumentthatdeterminesthestepbywhichtheslicingisdone.Thedefaultstepis1becauseofwhichitreturnsacontinuouspartofthetext.Givinganegativestep,i.e.,-1willreturnthetextinreverse.
Theinput()functiontakesastringasargumentanddisplaysittotheuser.Thenitwaitsfortheusertotypesomethingandpressthereturnkey.Oncetheuserhasenteredandpressedthereturnkey,theinput()functionwillthenreturnthattexttheuserhasentered.
Wetakethattextandreverseit.Iftheoriginaltextandreversedtextareequal,thenthetextisapalindrome.
Homeworkexercise
Checkingwhetheratextisapalindromeshouldalsoignorepunctuation,spacesandcase.Forexample,"Risetovote,sir."isalsoapalindromebutourcurrentprogramdoesn'tsayitis.Canyouimprovetheaboveprogramtorecognizethispalindrome?
Ifyouneedahint,theideaisthat...1
FilesYoucanopenandusefilesforreadingorwritingbycreatinganobjectofthefileclassandusingitsread,readlineorwritemethodsappropriatelytoreadfromorwritetothefile.Theabilitytoreadorwritetothefiledependsonthemodeyouhavespecifiedforthefileopening.Thenfinally,whenyouarefinishedwiththefile,youcalltheclosemethodtotellPythonthatwearedoneusingthefile.
Example(saveasio_using_file.py):
AByteofPython
112InputandOutput
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
First,openafilebyusingthebuilt-inopenfunctionandspecifyingthenameofthefileandthemodeinwhichwewanttoopenthefile.Themodecanbeareadmode('r'),writemode('w')orappendmode('a').Wecanalsospecifywhetherwearereading,writing,orappendingintextmode('t')orbinarymode('b').Thereareactuallymanymoremodesavailableandhelp(open)willgiveyoumoredetailsaboutthem.Bydefault,open()considersthefiletobea't'extfileandopensitin'r'eadmode.
Inourexample,wefirstopenthefileinwritetextmodeandusethewritemethodofthefileobjecttowritetothefileandthenwefinallyclosethefile.
AByteofPython
113InputandOutput
Next,weopenthesamefileagainforreading.Wedon'tneedtospecifyamodebecause'readtextfile'isthedefaultmode.Wereadineachlineofthefileusingthereadlinemethodinaloop.Thismethodreturnsacompletelineincludingthenewlinecharacterattheendoftheline.Whenanemptystringisreturned,itmeansthatwehavereachedtheendofthefileandwe'break'outoftheloop.
Intheend,wefinallyclosethefile.
Now,checkthecontentsofthepoem.txtfiletoconfirmthattheprogramhasindeedwrittentoandreadfromthatfile.
PicklePythonprovidesastandardmodulecalledpickleusingwhichyoucanstoreanyplainPythonobjectinafileandthengetitbacklater.Thisiscalledstoringtheobjectpersistently.
Example(saveasio_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)
Output:
$pythonio_pickle.py
['apple','mango','carrot']
HowItWorks
AByteofPython
114InputandOutput
Tostoreanobjectinafile,wehavetofirstopenthefileinwritebinarymodeandthencallthedumpfunctionofthepicklemodule.Thisprocessiscalledpickling.
Next,weretrievetheobjectusingtheloadfunctionofthepicklemodulewhichreturnstheobject.Thisprocessiscalledunpickling.
UnicodeSofar,whenwehavebeenwritingandusingstrings,orreadingandwritingtoafile,wehaveusedsimpleEnglishcharactersonly.
NOTE:IfyouareusingPython2,andwewanttobeabletoreadandwriteothernon-Englishlanguages,weneedtousetheunicodetype,anditallstartswiththecharacteru,e.g.u"helloworld"
>>>"helloworld"
'helloworld'
>>>type("helloworld")
<class'str'>
>>>u"helloworld"
'helloworld'
>>>type(u"helloworld")
<class'str'>
WhenwereadorwritetoafileorwhenwetalktoothercomputersontheInternet,weneedtoconvertourunicodestringsintoaformatthatcanbesentandreceived,andthatformatiscalled"UTF-8".Wecanreadandwriteinthatformat,usingasimplekeywordargumenttoourstandardopenfunction:
#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
Youcanignoretheimportstatementfornow,we'llexplorethatindetailinthemoduleschapter.
AByteofPython
115InputandOutput
WheneverwewriteaprogramthatusesUnicodeliteralslikewehaveusedabove,wehavetomakesurethatPythonitselfistoldthatourprogramusesUTF-8,andwehavetoput#encoding=utf-8commentatthetopofourprogram.
Weuseio.openandprovidethe"encoding"and"decoding"argumenttotellPythonthatweareusingunicode.
Youshouldlearnmoreaboutthistopicbyreading:
"TheAbsoluteMinimumEverySoftwareDeveloperAbsolutely,PositivelyMustKnowAboutUnicodeandCharacterSets"PythonUnicodeHowtoPragmaticUnicodetalkbyNatBatchelder
SummaryWehavediscussedvarioustypesofinput/output,aboutfilehandling,aboutthepicklemoduleandaboutUnicode.
Next,wewillexploretheconceptofexceptions.
1.Useatuple(youcanfindalistofallpunctuationmarkshere)toholdalltheforbiddencharacters,thenusethemembershiptesttodeterminewhetheracharactershouldberemovedornot,i.e.forbidden=(!,?,.,...).↩
AByteofPython
116InputandOutput
ExceptionsExceptionsoccurwhenexceptionalsituationsoccurinyourprogram.Forexample,whatifyouaregoingtoreadafileandthefiledoesnotexist?Orwhatifyouaccidentallydeleteditwhentheprogramwasrunning?Suchsituationsarehandledusingexceptions.
Similarly,whatifyourprogramhadsomeinvalidstatements?ThisishandledbyPythonwhichraisesitshandsandtellsyouthereisanerror.
ErrorsConsiderasimpleprintfunctioncall.WhatifwemisspeltprintasPrint?Notethecapitalization.Inthiscase,Pythonraisesasyntaxerror.
>>>Print("HelloWorld")
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
NameError:name'Print'isnotdefined
>>>print("HelloWorld")
HelloWorld
ObservethataNameErrorisraisedandalsothelocationwheretheerrorwasdetectedisprinted.Thisiswhatanerrorhandlerforthiserrordoes.
ExceptionsWewilltrytoreadinputfromtheuser.Press[ctrl-d]andseewhathappens.
>>>s=input('Entersomething-->')
Entersomething-->Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
EOFError
PythonraisesanerrorcalledEOFErrorwhichbasicallymeansitfoundanendoffilesymbol(whichisrepresentedbyctrl-d)whenitdidnotexpecttoseeit.
HandlingExceptions
AByteofPython
117Exceptions
Wecanhandleexceptionsusingthetry..exceptstatement.Webasicallyputourusualstatementswithinthetry-blockandputallourerrorhandlersintheexcept-block.
Example(saveasexceptions_handle.py):
try:
text=input('Entersomething-->')
exceptEOFError:
print('WhydidyoudoanEOFonme?')
exceptKeyboardInterrupt:
print('Youcancelledtheoperation.')
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/errorsinsidethetryblockandthenputhandlersfortheappropriateerrors/exceptionsintheexceptclause/block.Theexceptclausecanhandleasinglespecifiederrororexception,oraparenthesizedlistoferrors/exceptions.Ifnonamesoferrorsorexceptionsaresupplied,itwillhandleallerrorsandexceptions.
Notethattherehastobeatleastoneexceptclauseassociatedwitheverytryclause.Otherwise,what'sthepointofhavingatryblock?
Ifanyerrororexceptionisnothandled,thenthedefaultPythonhandleriscalledwhichjuststopstheexecutionoftheprogramandprintsanerrormessage.Wehavealreadyseenthisinactionabove.
Youcanalsohaveanelseclauseassociatedwithatry..exceptblock.Theelseclauseisexecutedifnoexceptionoccurs.
AByteofPython
118Exceptions
Inthenextexample,wewillalsoseehowtogettheexceptionobjectsothatwecanretrieveadditionalinformation.
RaisingExceptionsYoucanraiseexceptionsusingtheraisestatementbyprovidingthenameoftheerror/exceptionandtheexceptionobjectthatistobethrown.
TheerrororexceptionthatyoucanraiseshouldbeaclasswhichdirectlyorindirectlymustbeaderivedclassoftheExceptionclass.
Example(saveasexceptions_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))
else:
print('Noexceptionwasraised.')
Output:
$pythonexceptions_raise.py
Entersomething-->a
ShortInputException:Theinputwas1long,expectedatleast3
$pythonexceptions_raise.py
Entersomething-->abc
Noexceptionwasraised.
HowItWorks
AByteofPython
119Exceptions
Here,wearecreatingourownexceptiontype.ThisnewexceptiontypeiscalledShortInputException.Ithastwofields-lengthwhichisthelengthofthegiveninput,andatleastwhichistheminimumlengththattheprogramwasexpecting.
Intheexceptclause,wementiontheclassoferrorwhichwillbestoredasthevariablenametoholdthecorrespondingerror/exceptionobject.Thisisanalogoustoparametersandargumentsinafunctioncall.Withinthisparticularexceptclause,weusethelengthandatleastfieldsoftheexceptionobjecttoprintanappropriatemessagetotheuser.
Try...FinallySupposeyouarereadingafileinyourprogram.Howdoyouensurethatthefileobjectisclosedproperlywhetherornotanexceptionwasraised?Thiscanbedoneusingthefinallyblock.
Savethisprogramasexceptions_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:
AByteofPython
120Exceptions
$pythonexceptions_finally.py
Programmingisfun
Pressctrl+cnow
^C!!Youcancelledthereadingfromthefile.
(Cleaningup:Closedthefile)
HowItWorks
Wedotheusualfile-readingstuff,butwehavearbitrarilyintroducedsleepingfor2secondsafterprintingeachlineusingthetime.sleepfunctionsothattheprogramrunsslowly(Pythonisveryfastbynature).Whentheprogramisstillrunning,pressctrl+ctointerrupt/canceltheprogram.
ObservethattheKeyboardInterruptexceptionisthrownandtheprogramquits.However,beforetheprogramexits,thefinallyclauseisexecutedandthefileobjectisalwaysclosed.
Notethatweusesys.stdout.flush()afterprintsothatitprintstothescreenimmediately.
ThewithstatementAcquiringaresourceinthetryblockandsubsequentlyreleasingtheresourceinthefinallyblockisacommonpattern.Hence,thereisalsoawithstatementthatenablesthistobedoneinacleanmanner:
Saveasexceptions_using_with.py:
withopen("poem.txt")asf:
forlineinf:
print(line,end='')
HowItWorks
Theoutputshouldbesameasthepreviousexample.Thedifferencehereisthatweareusingtheopenfunctionwiththewithstatement-weleavetheclosingofthefiletobedoneautomaticallybywithopen.
Whathappensbehindthescenesisthatthereisaprotocolusedbythewithstatement.Itfetchestheobjectreturnedbytheopenstatement,let'scallit"thefile"inthiscase.
Italwayscallsthethefile.__enter__functionbeforestartingtheblockofcodeunderitandalwayscallsthefile.__exit__afterfinishingtheblockofcode.
AByteofPython
121Exceptions
Sothecodethatwewouldhavewritteninafinallyblockshouldbetakencareofautomaticallybythe__exit__method.Thisiswhathelpsustoavoidhavingtouseexplicittry..finallystatementsrepeatedly.
Morediscussiononthistopicisbeyondscopeofthisbook,sopleasereferPEP343foracomprehensiveexplanation.
SummaryWehavediscussedtheusageofthetry..exceptandtry..finallystatements.Wehaveseenhowtocreateourownexceptiontypesandhowtoraiseexceptionsaswell.
Next,wewillexplorethePythonStandardLibrary.
AByteofPython
122Exceptions
StandardLibraryThePythonStandardLibrarycontainsahugenumberofusefulmodulesandispartofeverystandardPythoninstallation.ItisimportanttobecomefamiliarwiththePythonStandardLibrarysincemanyproblemscanbesolvedquicklyifyouarefamiliarwiththerangeofthingsthattheselibrariescando.
Wewillexploresomeofthecommonlyusedmodulesinthislibrary.YoucanfindcompletedetailsforallofthemodulesinthePythonStandardLibraryinthe'LibraryReference'sectionofthedocumentationthatcomeswithyourPythoninstallation.
Letusexploreafewusefulmodules.
CAUTION:Ifyoufindthetopicsinthischaptertooadvanced,youmayskipthischapter.However,IhighlyrecommendcomingbacktothischapterwhenyouaremorecomfortablewithprogrammingusingPython.
sysmoduleThesysmodulecontainssystem-specificfunctionality.Wehavealreadyseenthatthesys.argvlistcontainsthecommand-linearguments.
SupposewewanttochecktheversionofthePythonsoftwarebeingused,thesysmodulegivesusthatinformation.
>>>importsys
>>>sys.version_info
sys.version_info(major=3,minor=5,micro=1,releaselevel='final',serial=0)
>>>sys.version_info.major==3
True
HowItWorks
Thesysmodulehasaversion_infotuplethatgivesustheversioninformation.Thefirstentryisthemajorversion.Wecanpulloutthisinformationtouseit.
loggingmodule
AByteofPython
123StandardLibrary
Whatifyouwantedtohavesomedebuggingmessagesorimportantmessagestobestoredsomewheresothatyoucancheckwhetheryourprogramhasbeenrunningasyouwouldexpectit?Howdoyou"storesomewhere"thesemessages?Thiscanbeachievedusingtheloggingmodule.
Saveasstdlib_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(
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
Ifyoudonothavethecatcommand,thenyoucanjustopenthetest.logfileinatexteditor.
HowItWorks
AByteofPython
124StandardLibrary
Weusethreemodulesfromthestandardlibrary-theosmoduleforinteractingwiththeoperatingsystem,theplatformmoduleforinformationabouttheplatformi.e.theoperatingsystemandtheloggingmoduletologinformation.
First,wecheckwhichoperatingsystemweareusingbycheckingthestringreturnedbyplatform.platform()(formoreinformation,seeimportplatform;help(platform)).IfitisWindows,wefigureoutthehomedrive,thehomefolderandthefilenamewherewewanttostoretheinformation.Puttingthesethreepartstogether,wegetthefulllocationofthefile.Forotherplatforms,weneedtoknowjustthehomefolderoftheuserandwegetthefulllocationofthefile.
Weusetheos.path.join()functiontoputthesethreepartsofthelocationtogether.Thereasontouseaspecialfunctionratherthanjustaddingthestringstogetherisbecausethisfunctionwillensurethefulllocationmatchestheformatexpectedbytheoperatingsystem.
Weconfiguretheloggingmoduletowriteallthemessagesinaparticularformattothefilewehavespecified.
Finally,wecanputmessagesthatareeithermeantfordebugging,information,warningorevencriticalmessages.Oncetheprogramhasrun,wecancheckthisfileandwewillknowwhathappenedintheprogram,eventhoughnoinformationwasdisplayedtotheuserrunningtheprogram.
ModuleoftheWeekSeriesThereismuchmoretobeexploredinthestandardlibrarysuchasdebugging,handlingcommandlineoptions,regularexpressionsandsoon.
ThebestwaytofurtherexplorethestandardlibraryistoreadDougHellmann'sexcellentPythonModuleoftheWeekseries(alsoavailableasabook)andreadingthePythondocumentation.
SummaryWehaveexploredsomeofthefunctionalityofmanymodulesinthePythonStandardLibrary.ItishighlyrecommendedtobrowsethroughthePythonStandardLibrarydocumentationtogetanideaofallthemodulesthatareavailable.
Next,wewillcovervariousaspectsofPythonthatwillmakeourtourofPythonmorecomplete.
AByteofPython
125StandardLibrary
MoreSofarwehavecoveredamajorityofthevariousaspectsofPythonthatyouwilluse.Inthischapter,wewillcoversomemoreaspectsthatwillmakeourknowledgeofPythonmorewell-rounded.
PassingtuplesaroundEverwishedyoucouldreturntwodifferentvaluesfromafunction?Youcan.Allyouhavetodoisuseatuple.
>>>defget_error_details():
...return(2,'details')
...
>>>errnum,errstr=get_error_details()
>>>errnum
2
>>>errstr
'details'
Noticethattheusageofa,b=<someexpression>interpretstheresultoftheexpressionasatuplewithtwovalues.
ThisalsomeansthefastestwaytoswaptwovariablesinPythonis:
>>>a=5;b=8
>>>a,b
(5,8)
>>>a,b=b,a
>>>a,b
(8,5)
SpecialMethodsTherearecertainmethodssuchasthe__init__and__del__methodswhichhavespecialsignificanceinclasses.
Specialmethodsareusedtomimiccertainbehaviorsofbuilt-intypes.Forexample,ifyouwanttousethex[key]indexingoperationforyourclass(justlikeyouuseitforlistsandtuples),thenallyouhavetodoisimplementthe__getitem__()methodandyourjobis
AByteofPython
126More
done.Ifyouthinkaboutit,thisiswhatPythondoesforthelistclassitself!
Someusefulspecialmethodsarelistedinthefollowingtable.Ifyouwanttoknowaboutallthespecialmethods,seethemanual.
__init__(self,...)
Thismethodiscalledjustbeforethenewlycreatedobjectisreturnedforusage.__del__(self)
Calledjustbeforetheobjectisdestroyed(whichhasunpredictabletiming,soavoidusingthis)
__str__(self)
Calledwhenweusetheprintfunctionorwhenstr()isused.__lt__(self,other)
Calledwhenthelessthanoperator(<)isused.Similarly,therearespecialmethodsforalltheoperators(+,>,etc.)
__getitem__(self,key)
Calledwhenx[key]indexingoperationisused.__len__(self)
Calledwhenthebuilt-inlen()functionisusedforthesequenceobject.
SingleStatementBlocksWehaveseenthateachblockofstatementsissetapartfromtherestbyitsownindentationlevel.Well,thereisonecaveat.Ifyourblockofstatementscontainsonlyonesinglestatement,thenyoucanspecifyitonthesamelineof,say,aconditionalstatementorloopingstatement.Thefollowingexampleshouldmakethisclear:
>>>flag=True
>>>ifflag:print('Yes')
...
Yes
Noticethatthesinglestatementisusedin-placeandnotasaseparateblock.Although,youcanusethisformakingyourprogramsmaller,Istronglyrecommendavoidingthisshort-cutmethod,exceptforerrorchecking,mainlybecauseitwillbemucheasiertoaddanextrastatementifyouareusingproperindentation.
AByteofPython
127More
LambdaFormsAlambdastatementisusedtocreatenewfunctionobjects.Essentially,thelambdatakesaparameterfollowedbyasingleexpressiononlywhichbecomesthebodyofthefunctionandthevalueofthisexpressionisreturnedbythenewfunction.
Example(saveasmore_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
Noticethatthesortmethodofalistcantakeakeyparameterwhichdetermineshowthelistissorted(usuallyweknowonlyaboutascendingordescendingorder).Inourcase,wewanttodoacustomsort,andforthatweneedtowriteafunctionbutinsteadofwritingaseparatedefblockforafunctionthatwillgetusedinonlythisoneplace,weusealambdaexpressiontocreateanewfunction.
ListComprehensionListcomprehensionsareusedtoderiveanewlistfromanexistinglist.Supposeyouhavealistofnumbersandyouwanttogetacorrespondinglistwithallthenumbersmultipliedby2onlywhenthenumberitselfisgreaterthan2.Listcomprehensionsareidealforsuchsituations.
Example(saveasmore_list_comprehension.py):
listone=[2,3,4]
listtwo=[2*iforiinlistoneifi>2]
print(listtwo)
Output:
AByteofPython
128More
$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*prefixontheargsvariable,allextraargumentspassedtothefunctionarestoredinargsasatuple.Ifa**prefixhadbeenusedinstead,theextraparameterswouldbeconsideredtobekey/valuepairsofadictionary.
TheassertstatementTheassertstatementisusedtoassertthatsomethingistrue.Forexample,ifyouareverysurethatyouwillhaveatleastoneelementinalistyouareusingandwanttocheckthis,andraiseanerrorifitisnottrue,thenassertstatementisidealinthissituation.Whentheassertstatementfails,anAssertionErrorisraised.
AByteofPython
129More
>>>mylist=['item']
>>>assertlen(mylist)>=1
>>>mylist.pop()
'item'
>>>assertlen(mylist)>=1
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
AssertionError
Theassertstatementshouldbeusedjudiciously.Mostofthetime,itisbettertocatchexceptions,eitherhandletheproblemordisplayanerrormessagetotheuserandthenquit.
DecoratorsDecoratorsareashortcuttoapplyingwrapperfunctions.Thisishelpfulto"wrap"functionalitywiththesamecodeoverandoveragain.Forexample,IcreatedaretrydecoratorformyselfthatIcanjustapplytoanyfunctionandifanyexceptionisthrownduringarun,itisretriedagain,tillamaximumof5timesandwithadelaybetweeneachretry.Thisisespeciallyusefulforsituationswhereyouaretryingtomakeanetworkcalltoaremotecomputer:
AByteofPython
130More
fromtimeimportsleep
fromfunctoolsimportwraps
importlogging
logging.basicConfig()
log=logging.getLogger("retry")
defretry(f):
@wraps(f)
defwrapped_f(*args,**kwargs):
MAX_ATTEMPTS=5
forattemptinrange(1,MAX_ATTEMPTS+1):
try:
returnf(*args,**kwargs)
except:
log.exception("Attempt%s/%sfailed:%s",
attempt,
MAX_ATTEMPTS,
(args,kwargs))
sleep(10*attempt)
log.critical("All%sattemptsfailed:%s",
MAX_ATTEMPTS,
(args,kwargs))
returnwrapped_f
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:
AByteofPython
131More
$pythonmore_decorator.py
Writetoadatabaseormakeanetworkcalloretc.
Thiswillbeautomaticallyretriedifexceptionisthrown.
ERROR:retry:Attempt1/5failed:(('Somebadvalue',),{})
Traceback(mostrecentcalllast):
File"more_decorator.py",line14,inwrapped_f
returnf(*args,**kwargs)
File"more_decorator.py",line39,insave_to_database
raiseValueError(arg)
ValueError:Somebadvalue
Writetoadatabaseormakeanetworkcalloretc.
Thiswillbeautomaticallyretriedifexceptionisthrown.
HowItWorks
See:
http://www.ibm.com/developerworks/linux/library/l-cpdecor.htmlhttp://toumorokoshi.github.io/dry-principles-through-python-decorators.html
DifferencesbetweenPython2andPython3See:
"Six"libraryPortingtoPython3ReduxbyArminPython3experiencebyPyDannyOfficialDjangoGuidetoPortingtoPython3DiscussiononWhataretheadvantagestopython3.x?
SummaryWehavecoveredsomemorefeaturesofPythoninthischapterandyetwehaven'tcoveredallthefeaturesofPython.However,atthisstage,wehavecoveredmostofwhatyouareevergoingtouseinpractice.Thisissufficientforyoutogetstartedwithwhateverprogramsyouaregoingtocreate.
Next,wewilldiscusshowtoexplorePythonfurther.
AByteofPython
132More
WhatNextIfyouhavereadthisbookthoroughlytillnowandpracticedwritingalotofprograms,thenyoumusthavebecomecomfortableandfamiliarwithPython.YouhaveprobablycreatedsomePythonprogramstotryoutstuffandtoexerciseyourPythonskillsaswell.Ifyouhavenotdoneitalready,youshould.Thequestionnowis'WhatNext?'.
Iwouldsuggestthatyoutacklethisproblem:
Createyourowncommand-lineaddress-bookprogramusingwhichyoucanbrowse,add,modify,deleteorsearchforyourcontactssuchasfriends,familyandcolleaguesandtheirinformationsuchasemailaddressand/orphonenumber.Detailsmustbestoredforlaterretrieval.
Thisisfairlyeasyifyouthinkaboutitintermsofallthevariousstuffthatwehavecome
acrosstillnow.Ifyoustillwantdirectionsonhowtoproceed,thenhere'sahint1.
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.
AByteofPython
133WhatNext
ExampleCodeThebestwaytolearnaprogramminglanguageistowritealotofcodeandreadalotofcode:
PythonCookbookisanextremelyvaluablecollectionofrecipesortipsonhowtosolvecertainkindsofproblemsusingPython.Thisisamust-readforeveryPythonuser.PythonModuleoftheWeekisanotherexcellentmust-readguidetotheStandardLibrary.
AdviceTheHitchhiker'sGuidetoPython!TheElementsofPythonStylePythonBigPicture"WritingIdiomaticPython"ebook(paid)
VideosFullStackWebDevelopmentwithFlaskPyVideo
QuestionsandAnswersOfficialPythonDosandDon'tsOfficialPythonFAQNorvig'slistofInfrequentlyAskedQuestionsPythonInterviewQ&AStackOverflowquestionstaggedwithpython
TutorialsHiddenfeaturesofPythonWhat'stheonecodesnippet/pythontrick/etcdidyouwishyouknewwhenyoulearnedpython?Awaretek'scomprehensivelistofPythontutorials
AByteofPython
134WhatNext
DiscussionIfyouarestuckwithaPythonproblem,anddon'tknowwhomtoask,thenthepython-tutorlististhebestplacetoaskyourquestion.
Makesureyoudoyourhomeworkbytryingtosolvingtheproblemyourselffirstandasksmartquestions.
NewsIfyouwanttolearnwhatisthelatestintheworldofPython,thenfollowtheOfficialPythonPlanet.
InstallinglibrariesThereareahugenumberofopensourcelibrariesatthePythonPackageIndexwhichyoucanuseinyourownprograms.
Toinstallandusetheselibraries,youcanusepip.
CreatingaWebsiteLearnFlasktocreateyourownwebsite.Someresourcestogetstarted:
FlaskOfficialQuickstartTheFlaskMega-TutorialExampleFlaskProjects
GraphicalSoftwareSupposeyouwanttocreateyourowngraphicalprogramsusingPython.ThiscanbedoneusingaGUI(GraphicalUserInterface)librarywiththeirPythonbindings.BindingsarewhatallowyoutowriteprogramsinPythonandusethelibrarieswhicharethemselveswritteninCorC++orotherlanguages.
TherearelotsofchoicesforGUIusingPython:
Kivy
http://kivy.org
AByteofPython
135WhatNext
PyGTK
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).
VariousImplementationsThereareusuallytwopartsaprogramminglanguage-thelanguageandthesoftware.Alanguageishowyouwritesomething.Thesoftwareiswhatactuallyrunsourprograms.
AByteofPython
136WhatNext
WehavebeenusingtheCPythonsoftwaretorunourprograms.ItisreferredtoasCPythonbecauseitiswrittenintheClanguageandistheClassicalPythoninterpreter.
TherearealsoothersoftwarethatcanrunyourPythonprograms:
Jython
APythonimplementationthatrunsontheJavaplatform.ThismeansyoucanuseJavalibrariesandclassesfromwithinPythonlanguageandvice-versa.
IronPython
APythonimplementationthatrunsonthe.NETplatform.Thismeansyoucanuse.NETlibrariesandclassesfromwithinPythonlanguageandvice-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
Summary
AByteofPython
137WhatNext
Wehavenowcometotheendofthisbookbut,astheysay,thisisthethebeginningoftheend!.YouarenowanavidPythonuserandyouarenodoubtreadytosolvemanyproblemsusingPython.Youcanstartautomatingyourcomputertodoallkindsofpreviouslyunimaginablethingsorwriteyourowngamesandmuchmuchmore.So,getstarted!
1.Createaclasstorepresenttheperson'sinformation.Useadictionarytostorepersonobjectswiththeirnameasthekey.Usethepicklemoduletostoretheobjectspersistentlyonyourharddisk.Usethedictionarybuilt-inmethodstoadd,deleteandmodifythepersons.↩
AByteofPython
138WhatNext
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(including
AByteofPython
139Appendix:FLOSS
MicrosoftIIS)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
So,goaheadandexplorethevast,freeandopenworldofFLOSS!
AByteofPython
140Appendix:FLOSS
Appendix:ColophonAlmostallofthesoftwarethatIhaveusedinthecreationofthisbookareFLOSS.
BirthoftheBookInthefirstdraftofthisbook,IhadusedRedHat9.0Linuxasthefoundationofmysetupandinthesixthdraft,IusedFedoraCore3Linuxasthebasisofmysetup.
Initially,IwasusingKWordtowritethebook(asexplainedinthehistorylesson).
TeenageYearsLater,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
AByteofPython
141Appendix:About
2016:IgottiredofseveralminorrenderingissuesinAsciiDoctor,likethe++inC/C++woulddisappearanditwashardtokeeptrackofescapingsuchminorthings.Plus,IhadbecomereluctanttoeditthetextbecauseofthecomplexAsciidocformat.
Forthetenthdraft,IswitchedtowritinginMarkdown+GitBookformat,usingtheSpacemacseditor.
AbouttheAuthorSeehttp://www.swaroopch.com/about/
AByteofPython
142Appendix:About
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:RevisionHistory4.0
AByteofPython
143Appendix:RevisionHistory
19Jan2016SwitchedbacktoPython3SwitchedbacktoMarkdown,usingGitBookandSpacemacs
3.0
31Mar2014RewrittenforPython2usingAsciiDocandadoc-mode.
2.1
03Aug2013RewrittenusingMarkdownandJasonBlevins'MarkdownMode
2.0
20Oct2012RewritteninPandocformat,thankstomywifewhodidmostoftheconversionfromtheMediawikiformatSimplifyingtext,removingnon-essentialsectionssuchasnonlocalandmetaclasses
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
08Mar2004
AByteofPython
144Appendix:RevisionHistory
Aftertremendousfeedbackandsuggestionsfromreaders,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.
0.90
18Dec2003Added2morechapters.OpenOfficeformatwithrevisions.
0.60
21Nov2003Fullyrewrittenandexpanded.
0.20
20Nov2003Correctedsometyposanderrors.
0.15
20Nov2003
AByteofPython
145Appendix:RevisionHistory
ConvertedtoDocBookXMLwithXEmacs.0.10
14Nov2003InitialdraftusingKWord.
AByteofPython
146Appendix:RevisionHistory
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.
Catalan
AByteofPython
147Appendix:Translations
MoisesGomez([email protected])hasvolunteeredtotranslatethebooktoCatalan.Thetranslationisinprogress.
MoisèsGómez-Iamadeveloperandalsoateacherofprogramming(normallyforpeoplewithoutanypreviousexperience).
SometimeagoIneededtolearnhowtoprograminPython,andSwaroop'sworkwasreallyhelpful.Clear,concise,andcompleteenough.JustwhatIneeded.
Afterthisexperience,Ithoughtsomeotherpeopleinmycountrycouldtakebenefitfromittoo.ButEnglishlanguagecanbeabarrier.
So,whynottrytotranslateit?AndIdidforapreviousversionofBoP.
Imycountrytherearetwoofficiallanguages.IselectedtheCatalanlanguageassumingthatotherswilltranslateittothemorewidespreadSpanish.
ChineseTranslationsareavailableathttp://woodpecker.org.cn/abyteofpython_cn/chinese/andhttp://zhgdg.gitcafe.com/static/doc/byte_of_python.html.
JuanShen([email protected])hasvolunteeredtotranslatethebooktoChinese.
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.
ChineseTraditionalFredLin([email protected])hasvolunteeredtotranslatethebooktoChineseTraditional.
Itisavailableathttp://code.google.com/p/zhpy/wiki/ByteOfZhpy.
AByteofPython
148Appendix:Translations
Anexcitingfeatureofthistranslationisthatitalsocontainstheexecutablechinesepythonsourcessidebysidewiththeoriginalpythonsources.
FredLin-I'mworkingasanetworkfirmwareengineeratDeltaNetwork,andI'malsoacontributorofTurboGearswebframework.
Asapythonevangelist(:-p),Ineedsomematerialtopromotepythonlanguage.Ifound'AByteofPython'hitthesweetpointforbothnewbiesandexperiencedprogrammers.'AByteofPython'elaboratesthepythonessentialswithaffordablesize.
Thetranslationareoriginallybasedonsimplifiedchineseversion,andsoonalotofrewriteweremadetofitthecurrentwikiversionandthequalityofreading.
Therecentchinesetraditionalversionalsofeaturedwithexecutablechinesepythonsources,whichareachievedbymynew'zhpy'(pythoninchinese)project(launchfromAug07).
zhpy(pronounce(Z.H.?,orzippy)buildalayeruponpythontotranslateorinteractwithpythoninchinese(TraditionalorSimplified).Thisprojectismainlyaimedforeducation.
FrenchGregory([email protected])hasvolunteeredtotranslatethebooktoFrench.
GérardLabadie([email protected])hascompletedtotranslatethebooktoFrench.
GermanLutzHorn([email protected]),BerndHengelein([email protected])andChristophZwerschke([email protected])havevolunteeredtotranslatethebooktoGerman.
Theirtranslationislocatedathttp://ftp.jaist.ac.jp/pub//sourceforge/a/ab/abop-german.berlios/
LutzHornsays:
AByteofPython
149Appendix:Translations
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!
Greek
AByteofPython
150Appendix:Translations
TheGreekUbuntuCommunitytranslatedthebookinGreek,foruseinouron-lineasynchronousPythonlessonsthattakeplaceinourforums.Contact@savvasradevicformoreinformation.
IndonesianDaniel([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
AByteofPython
151Appendix:Translations
ShunroDozono([email protected])istranslatingthebooktoJapanese.
KoreanJeongbinPark([email protected])hastranslatedthebooktoKorean-https://github.com/pjb7687/byte_of_python
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).
AByteofPython
152Appendix:Translations
EirikVågeskar:Ihavealwayswantedtoprogram,butbecauseIspeakasmalllanguage,thelearningprocesswasmuchharder.MosttutorialsandbooksarewritteninverytechnicalEnglish,somosthighschoolgraduateswillnotevenhavethevocabularytounderstandwhatthetutorialisabout.WhenIdiscoveredthisbook,allmyproblemsweresolved."AByteofPython"usedsimplenon-technicallanguagetoexplainaprogramminglanguagethatisjustassimple,andthesetwothingsmakelearningPythonfun.Afterreadinghalfofthebook,Idecidedthatthebookwasworthtranslating.Ihopethetranslationwillhelppeoplewhohavefoundthemselfinthesamesituationasme(especiallyyoungpeople),andmaybehelpspreadinterestforthelanguageamongpeoplewithlesstechnicalknowledge.
PolishDominikKozaczko([email protected])hasvolunteeredtotranslatethebooktoPolish.Translationisinprogressandit'smainpageisavailablehere:UkąśPythona.
Update:ThetranslationiscompleteandreadyasofOct2,2009.ThankstoDominik,histwostudentsandtheirfriendfortheirtimeandeffort!
DominikKozaczko-I'maComputerScienceandInformationTechnologyteacher.
PortugueseFidelViegas([email protected])hasvolunteeredtotranslatethebooktoPortuguese.
RomanianPaul-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
AByteofPython
153Appendix:Translations
VladimirSmolyar([email protected])hascompletedaRussiantranslationathttp://wombat.org.ua/AByteOfPython/.
UkranianAverkievAndrey([email protected])hasvolunteeredtotranslatethebooktoRussian,andperhapsUkranian(timepermitting).
Serbian"BugSpice"([email protected])hascompletedaSerbiantranslation:
Thisdownloadlinkisnolongeraccessible.
Moredetailsathttp://forum.ubuntu-rs.org/Thread-zagrljaj-pitona.
SlovakAlbertioWard([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:
AByteofPython
154Appendix:Translations
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."
AByteofPython
155Appendix:Translations
TranslationHow-to1. Thefullsourceofthebookisavailablefromhttps://github.com/swaroopch/byte-of-
python.2. Pleaseforktherepository.3. Then,fetchtherepositorytoyourcomputer.YouneedtoknowhowtouseGittodothat.4. ReadtheGitBookdocumentation,esp.theMarkdownsection.5. Starteditingthe.mdfilestotranslatetoyourlocallanguage.6. SignuponGitBook.com,createabookandyoucanseeabeautifullyrenderedwebsite,
withlinkstodownloadPDF,EPUB,etc.
AByteofPython
156Appendix:TranslationHow-to
FeedbackThebookneedsthehelpofitsreaderssuchasyourselvestopointoutanypartsofthebookwhicharenotgood,notcomprehensibleoraresimplywrong.Pleasewritetothemainauthorortherespectivetranslatorswithyourcommentsandsuggestions.
AByteofPython
157Feedback