Vous êtes sur la page 1sur 165

1/4/2015

AByteofPython

AByteofPython
SwaroopCH
swaroop@swaroopch.com

http://www.swaroopch.com/notes/python/

1/165

1/4/2015

AByteofPython

TableofContents
1.Welcome
2.Dedication
3.Preface
4.Introduction
5.Installation
6.FirstSteps
7.Basics
8.OperatorsandExpressions
9.ControlFlow
10.Functions
11.Modules
12.DataStructures
13.ProblemSolving
14.ObjectOrientedProgramming
15.InputandOutput
16.Exceptions
17.StandardLibrary
18.More
19.Appendix:FLOSS
20.Appendix:Colophon
21.Appendix:HistoryLesson
22.Appendix:RevisionHistory
23.Translations
24.TranslationHowto

http://www.swaroopch.com/notes/python/

2/165

1/4/2015

AByteofPython

"AByteofPython"isafreebookonprogrammingusingthePythonlanguage.It
servesasatutorialorguidetothePythonlanguageforabeginneraudience.Ifallyou
knowaboutcomputersishowtosavetextfiles,thenthisisthebookforyou.

http://www.swaroopch.com/notes/python/

3/165

1/4/2015

AByteofPython

1.Welcome
1.1.WhoreadsAByteofPython?
Herearewhatpeoplearesayingaboutthebook:

ThisisthebestbeginnerstutorialIveeverseen!Thankyouforyoureffort.

Thebestthingifoundwas"AByte ofPython",whichissimplyabrilliantbookfor

WaltMichalik

a beginner. Its well written, the concepts are well explained with self evident
examples.
JoshuaRobin

Excellentgentleintroductiontoprogramming#Pythonforbeginners

Bestnewbieguidetopython

starttolovepythonwitheverysinglepageread

perfect beginners guide for python, will give u key to unlock magical world of

ShanRajasekaran (https://twitter.com/ShanRajasekaran/status/268910645842423809)

NicksonKaigi (https://twitter.com/nickaigi/status/175508815729541120)

HerbertFeutl (https://twitter.com/HerbertFeutl/status/11901471389913088)

python
Dilip (https://twitter.com/Dili_mathilakam/status/220033783066411008)

I should be doing my actual "work" but just found "A Byte of Python". A great
guidewithgreatexamples.
BiologistJohn (https://twitter.com/BiologistJohn/statuses/194726001803132928)

Recently started reading a Byte of python.Awesome work. And that too for free.
Highlyrecommendedforaspiringpythonistas.
Mangesh (https://twitter.com/mangeshnanoti/status/225680668867321857)

http://www.swaroopch.com/notes/python/

4/165

1/4/2015

AByteofPython

A Byte of Python, written by Swaroop. (this is the book Im currently reading).


Probably the best to start with, and probably the best in the world for every
newbieorevenamoreexperienceduser.
Apostolos (http://apas.gr/2010/04/27/learningpython/)

EnjoyingReading#ByteOfPythonby@swaroopchbestbookever

Thank you so much for writing A Byte Of Python. I just started learning how to

YuvrajSharma (https://twitter.com/YuvrajPoudyal/status/448050415356346368)

code two days ago and Im already building some simple games. Your guide has
beenadreamandIjustwantedtoletyouknowhowvaluableithasbeen.
Franklin

Im from Dayanandasagar College of Engineering (7th sem, CSE). Firstly i want


to say that your book "The byte of python" is too good a book for a beginner in
python like me.The concepts are so well explained with simple examples that
helpedmetoeasilylearnpython.Thankyousomuch.
Madhura

I am a 18 year old IT student studying at University in Ireland. I would like to


express my gratitude to you for writing your book "A Byte of Python", I already
hadknowledgeof 3programminglangaguesC,Java andJavascript,andPython
was byfar theeasiest langagueI haveever learned,and thatwas mainlybecause
your book was fantastic and made learning python very simple and interesting. It
isone ofthe bestwrittenand easyto followprogrammingbooks Ihave everread.
Congratulationsandkeepupthegreatwork.
Matt

Hi, Imfrom DominicanRepublic. Myname isPavel, recentlyI readyour bookA


Byte of Pythonand I consider it excellent!! :). I learnt much from all the
examples.Yourbookisofgreathelpfornewbieslikeme
PavelSimo

http://www.swaroopch.com/notes/python/

5/165

1/4/2015

AByteofPython

I am a student from China, Now ,I have read you book A byte of Python, Oh its
beautiful. The bookis very simple but canhelp all the first learnners.You know I
am interesting in Java and cloud computing many times, i have to coding
programm for the server, so i think python is a good choice, finish your book, i
think its not only a good choice its must use the Python. My English is not very
well, the email to you, i just wanna thank you! Best Wishes for you and your
family.
RoyLau

I recently finished reading Byte of Python, and I thought I really ought to thank
you. I was very sad to reach the final pages as I now have to go back to dull,
tedious oreilly or etc. manuals for learning about python. Anyway, I really
appreciateyourbook.
SamuelYoung

Dear Swaroop, I am taking a class from an instructor that has no interest in


teaching. We are using Learning Python, second edition, by OReilly. It is not a
text for beginner without any programming knowledge, and an instructor that
shouldbeworking inanotherfield.Thankyouverymuch foryourbook,withoutit
I would be clueless about Python and programming. Thanks a million, you are
able tobreak themessage downto a level that beginnerscan understand and not
everyonecan.
JosephDuarte

I love your book! It is the greatest Python tutorial ever, and a very useful
reference.Brilliant,atruemasterpiece!Keepupthegoodwork!
ChrisAndrSommerseth

http://www.swaroopch.com/notes/python/

6/165

1/4/2015

AByteofPython

First of all, I want to say thanks to you for this greate book. I think it is a good
bookforthosewhoarelookingforabeginnerstutorialforPython.
It is abouttwo or there yearsago, I think, when Ifirst heard of thisbook.At that
time, I am not able to read some book in English yet, so I got a chinese
translation,whichtookmeintothegateofPythonprogramming.
Recently, I reread this book. This time, of course, the english version. I couldnt
believe that I can read the whole book without my dictionary at hand. Of course,
itallduestoyourefforttomakethisbookaneasytounderstandone.
myd7349 (https://github.com/swaroopch/byte_of_python/pull/13)

Im just emailing you to thank you for writing Byte of Python online. I had been
attempting Python for a few months prior to stumbling across your book, and
althoughImadelimitedsuccesswithpyGame,Inevercompletedaprogram.
Thanksto yoursimplificationofthe categories,Pythonactuallyseems areachable
goal. It seems like I have finally learned the foundations and I can continue into
myrealgoal,gamedevelopment.

Onceagain, thanksVERYmuch forplacingsucha structuredandhelpful guideto


basic programming on the web. It shoved me into and out of OOP with an
understandingwheretwotextbookshadfailed.
MattGallivan

http://www.swaroopch.com/notes/python/

7/165

1/4/2015

AByteofPython

I would like to thank you for your book A Byte of Pythonwhich i myself find the
best way to learn python. I am a 15 year old i live in egypt my name isAhmed.
Pythonwas mysecond programminglanguagei learnvisualbasic 6at schoolbut
didnt enjoy it, however i really enjoyed learning python. I made the addressbook
program and i was sucessful. i will try to start make more programs and read
python programs (if you could tell me source that would be helpful). I will also
start on learning java and if you can tell me where to find a tutorial as good as
yoursforjavathatwouldhelpmealot.Thanx.
AhmedMohammed

A wonderful resource for beginners wanting to learn more about Python is the
110page PDF tutorialAByte of Python by Swaroop C H.It is wellwritten, easy
tofollow,andmaybethebestintroductiontoPythonprogrammingavailable.
DrewAmes (http://www.linux.com/feature/126522)

Yesterday I got through most of Byte of Python on my Nokia N800 and its the
easiest and most concise introduction to Python I have yet encountered. Highly
recommendedasastartingpointforlearningPython.
JasonDelport (http://paxmodept.com/telesto/blogitem.htm?id=627)

Byte of Vim and Python by @swaroopch is by far the best works in technical
writingtome.Excellentreads#FeelGoodFactor
Surendran (http://twitter.com/suren/status/12840485454)

"Byteofpython"bestonebyfarman
(inresponse tothequestion"Can anyonesuggestagood, inexpensiveresourcefor
learningthebasicsofPython?")
JustinLoveTrue (http://www.facebook.com/pythonlang/posts/406873916788)

TheBookByteofpythonwasveryhelpful..Thanksbigtime:)
Chinmay (https://twitter.com/a_chinmay/status/258822633741762560)

http://www.swaroopch.com/notes/python/

8/165

1/4/2015

AByteofPython

Always been a fan of A Byte of Python made for both new and experienced
programmers.
PatrickHarrington (http://stackoverflow.com/a/457785/4869)

I started learning python few days ago from your book..thanks for such a nice
book. it is so well written, you made my life easy..so you found a new fan of
yours..thatsme:)tonsofthanks.
GadadhariBheem (https://twitter.com/Pagal_e_azam/statuses/242865885256232960)

Before I started to learn Python, Ive acquired basic programming skills in


Assembly, C,C++, C# and Java.The very reason Iwanted to learn Pythonis its
popular (people are talking about it) and powerful (reality). This book written by
Mr. Swaroop is a very good guide for both brandnew programmers and new
pythonprogrammers.Took10halfdaystogothroughit.GreatHelp!
FangBiyi(PhDCandidateECE,MichiganStateUniversity)

Thankyoueversomuchforthisbook!!
This book cleared up many questions I had about certain aspects of Python such
asobjectorientedprogramming.
I do not feel like an expert at OO but I know this book helped me on a first step
ortwo.
I havenow writtenseveral pythonprograms thatactually doreal thingsfor meas
a system administrator. They are all procedural oriented but they are small by
mostpeoplesstandards.
Again,thanksforthisbook.Thankyouforhavingitontheweb.
Bob

http://www.swaroopch.com/notes/python/

9/165

1/4/2015

AByteofPython

Ijust wanttothankyou forwritingthefirst bookonprogrammingIve everreally


read.Python isnow myfirst language,andI canjust imagineall thepossibilities.
Sothank youforgiving methetools tocreatethings Ineverwould haveimagined
Icoulddobefore.
TheWalrus

I wantedto thank you forwriting A ByteOf Python(2 & 3 Versions). It has been
invaluabletomylearningexperienceinPython&Programmingingeneral.
Needlesstosay,I amabeginnerintheprogrammingworld,a coupleofmonthsof
selfstudy uptothis point.Ihad beenusingyoutube tutorials&some otheronline
tutorials including other free books. I decided to dig into your book yesterday, &
Ive learned more on the first few pages than any other book or tutorial. A few
thingsIhadbeenconfusedabout,were clearedrightupwithaGREATexample&
explanation.Cantwaittoread(andlearn)more!!
Thank you so much for not only writing the book, but for putting it under the
creative commons license (free). Thank goodness there are unselfish people like
yououttheretohelp&teachtherestofus.
Chris

http://www.swaroopch.com/notes/python/

10/165

1/4/2015

AByteofPython

I wrote you back in 2011 and I was just getting into Python and wanted to thank
you for your tutorial "A Byte of Python". Without it, I would have fallen by the
wayside. Since then I have gone on to program a number of functions in my
organization with this language with yet more on the horizon. I would not call
myselfanadvanced programmerbyanystretchbutI noticetheoccasionalrequest
forassistance nowfrom otherssinceI startedusing it.I discovered,while reading
"Byte" why Ihad ceased studying C andC[]+ and it was becausethe book given
to me started out with an example containing an augmented assignment. Of
course, there was no explanation for this arrangement of operators and I fell on
my head trying tomake sense of what was onthe written page. As I recallit was
a most frustrating exercise which I eventuallyabandoned. Doesn't mean C or C+
is impossible to learn, or even that I am stupid, but it does mean that the
documentation I worked my way through did not define the symbols and words
whichis anessentialpart ofanyinstruction. Justascomputers willnotbe ableto
understanda computerword orcomputersymbol thatisoutside thesyntax forthe
language being used, a student new to any field will not grasp his subject if he
encounters words or symbols for which there are no definitions. You get a "blue
screen" as it werein either case. The solution is simple, though:find the word or
symbolandget theproperdefinitionor symbolandloand behold,thecomputeror
studentcan proceed.Your bookwas sowell puttogether that Ifound verylittle in
it I couldnt grasp. So, thank you. I encourage you to continue to include full
definitions ofterms. The documentation with Python isgood, once you know, (the
examples are its strength from what I see) but in many cases it seems that you
have to know in order to understand the documentation which to my mind is not
what should be. Third party tutorials express the need for clarification of the
documentation and their success largely depends on the words that are used to
describethe terminology.Ihave recommendedyour bookto manyothers. Somein
Australia, some in the Caribbean and yet others in the US. It fills a niche no
othersdo.Ihopeyouaredoingwellandwishyouallthesuccessinthefuture.
Nick

http://www.swaroopch.com/notes/python/

11/165

1/4/2015

AByteofPython

hey, this is ankush(19). I was facing agreat difficulty to start with python. I tried
a lot of books but all were bulkier and not target oriented and then i found this
lovelyone, whichmademelove pythoninnotime. Thanksalotfor this"beautiful
pieceofbook".
Ankush

I would like to thank you for your excellent guide on Python. I am a molecular
biologist (with little programming background) and for my work I need to handle
big datasets of DNA sequences and to analyse microscope images. For both
things, programming in python has been useful, if not essential to complete and
publisha6yearsproject.
That such aguide is freely available is aclear sign that the forces ofevil are not
yetrulingtheworld!:)
Luca

Since this is going to be the first language you learn, you should use A Byte of
Python.It reallygives aproper introductioninto programmingin Pythonand itis
paced well enough for the average beginner. The most important thing from then
onwillbeactuallystartingtopracticemakingyourownlittleprograms.
"{Unregistered}"
(http://www.overclock.net/t/1177951/wanttolearnprogrammingwheredoistart#post_15837176)

Just to say a loud and happy thank you very muchfor publishing "A Byte of
Python" and "A Byte of Vim". Those books were very useful to me four or five
years ago when I starting learning programming. Right now Im developing a
project that was a dream for a long, long time and just want to say thank you.
Keepwalking.Youareasourceofmotivation.Allthebest.
Jocimar

Finished reading A byte of Python in 3 days. It is thoroughly interesting. Not a


single page was boring. I want to understand the Orca screen reader code. Your
bookhashopefullyequippedmeforit.

http://www.swaroopch.com/notes/python/

12/165

1/4/2015

AByteofPython

Dattatray

Hi, 'A byte of python' is really a good reading for python beginners. So, again,
NICEWORK!
im a 4 years experienced Java&C developer from China. Recently, i want to do
someworkonzimwikinoteprojectwhichusespygtktoimplement.
i read your book in 6 days, and i can read and write python code examples now.
thx foryour contribution. plzkeep your enthusiasm tomake this worldbetter, this
isjustalittleencouragefromChina.YourreaderLee
LEE

I am Isen from Taiwan, who is a graduating PhD student in Electrical


Engineering Department ofNational Taiwan University. I would liketo thank you
foryour greatbook. Ithink itis notonlyjust easyto readbut alsocomprehensive
and complete for a new comer of Python. The reason I read your book is that I
am starting to work on the GNU Radio framework. Your book let me catch most
ofimportantcoreideasandskillofPythonwithaminimumtime.
I also sawthat you do notmind that readers sendyou a thank notein your book.
SoIreallylikeyourbookandappreciateit.Thanks.
IsenIChunChao

ThebookisevenusedbyNASA!ItisbeingusedintheirJetPropulsionLaboratory
(http://dsnra.jpl.nasa.gov/software/Python/byteofpython/output/byteofpython_html/)withtheirDeepSpace

Networkproject.

1.2.AcademicCourses
Thisbookis/wasbeingusedasinstructionalmaterialinvariouseducationalinstitutions:
'PrinciplesofProgrammingLanguages'courseat'VrijeUniversiteit,Amsterdam'
(http://www.few.vu.nl/~nsilvis/PPL/2007/index.html)

'BasicConceptsofComputing'courseat'UniversityofCalifornia,Davis'
(http://www.cs.ucdavis.edu/courses/exp_course_desc/10.html)
http://www.swaroopch.com/notes/python/

13/165

1/4/2015

AByteofPython

'ProgrammingWithPython'courseat'HarvardUniversity'
(http://www.people.fas.harvard.edu/~preshman/python_winter.html)

'IntroductiontoProgramming'courseat'UniversityofLeeds' (http://www.comp.leeds.ac.uk/acom1900/)
'IntroductiontoApplicationProgramming'courseat'BostonUniversity'
(http://www.cs.bu.edu/courses/cs108/materials.html)

'InformationTechnologySkillsforMeteorology'courseat'UniversityofOklahoma'
(http://gentry.metr.ou.edu/byteofpython/)

'Geoprocessing'courseat'MichiganStateUniversity' (http://www.msu.edu/~ashton/classes/825/index.html)
'MultiAgentSemanticWebSystems'courseatthe'UniversityofEdinburgh'
(http://homepages.inf.ed.ac.uk/ewan/masws/)

'IntroductiontoComputerScienceandProgramming'at'MITOpenCourseWare'
(http://ocw.mit.edu/courses/electricalengineeringandcomputerscience/600scintroductiontocomputerscience
andprogrammingspring2011/references/)

'BasicprogrammingattheFacultyofSocialSciences,UniversityofLjubljana,Slovenia'Ale
ibernasays"I(andmypredecessor)havebeenusingyourbookasthemainliteratureforthis
course"

1.3.License
ThisbookislicensedunderaCreativeCommonsAttributionShareAlike4.0InternationalLicense
(http://creativecommons.org/licenses/bysa/4.0/).

Thismeans:
YouarefreetoSharei.e.tocopy,distributeandtransmitthisbook
YouarefreetoRemixi.e.tomakechangestothisbook(especiallytranslations)
Youarefreetouseitforcommercialpurposes
Pleasenote:
Pleasedonotsellelectronicorprintedcopiesofthebookunlessyouhaveclearlyandprominently
mentionedinthedescriptionthatthesecopiesarenotfromtheoriginalauthorofthisbook.
Attributionmustbeshownintheintroductorydescriptionandfrontpageofthedocumentbylinking
backtohttp://swaroopch.com/notes/pythonandclearlyindicatingthattheoriginaltextcanbefetched
fromthislocation.

http://www.swaroopch.com/notes/python/

14/165

1/4/2015

AByteofPython

Allthecode/scriptsprovidedinthisbookislicensedunderthe3clauseBSDLicense
(http://www.opensource.org/licenses/bsdlicense.php)unlessotherwisenoted.

1.4.ReadNow
Youcanreadthebookonlineathttp://swaroopch.com/notes/python

1.5.BuyTheBook
Aprintedhardcopyofthebookcanbepurchasedathttp://swaroopch.com/buybookforyouroffline
readingpleasure,andtosupportthecontinueddevelopmentandimprovementofthisbook.

1.6.Download
PDF (http://files.swaroopch.com/python/byte_of_python.pdf)(fordesktopreading,etc.)
EPUB (http://files.swaroopch.com/python/byte_of_python.epub)(foriPhone/iPad,ebookreaders,etc.)
Mobi(forKindle) (http://files.swaroopch.com/python/byte_of_python.mobi)
GitHub (https://github.com/swaroopch/byte_of_python)(forrawtext,translating,etc.)
Ifyouwishtosupportthecontinueddevelopmentofthisbook,pleaseconsiderbuyingahardcopy
(http://swaroopch.com/buybook).

1.7.Readthebookinyournativelanguage
Ifyouareinterestedinreadingorcontributingtranslationsofthisbooktootherhumanlanguages,please
seeTranslations.

http://www.swaroopch.com/notes/python/

15/165

1/4/2015

AByteofPython

2.Dedication
ToKalyanVarma (http://www.kalyanvarma.net/)andmanyotherseniorsatPESIT (http://www.pes.edu/)who
introducedustoGNU/Linuxandtheworldofopensource.
TothememoryofAtulChitnis (http://www.nextbigwhat.com/atulchitnisobituary297/),afriendandguidewho
shallbemissedgreatly.
TothepioneerswhomadetheInternethappen (http://www.ibiblio.org/pioneers/index.html).Thisbookwas
firstwrittenin2003.Itstillremainspopular,thankstothenatureofsharingknowledgeontheInternetas
envisionedbythepioneers.

http://www.swaroopch.com/notes/python/

16/165

1/4/2015

AByteofPython

3.Preface
Pythonisprobablyoneofthefewprogramminglanguageswhichisbothsimpleandpowerful.Thisis
goodforbeginnersaswellasforexperts,andmoreimportantly,isfuntoprogramwith.Thisbookaims
tohelpyoulearnthiswonderfullanguageandshowhowtogetthingsdonequicklyandpainlesslyin
effect'TheAntivenomtoyourprogrammingproblems'.

3.1.WhoThisBookIsFor
ThisbookservesasaguideortutorialtothePythonprogramminglanguage.Itismainlytargetedat
newbies.Itisusefulforexperiencedprogrammersaswell.
Theaimisthatifallyouknowaboutcomputersishowtosavetextfiles,thenyoucanlearnPythonfrom
thisbook.Ifyouhavepreviousprogrammingexperience,thenyoucanalsolearnPythonfromthisbook.
Ifyoudohavepreviousprogrammingexperience,youwillbeinterestedinthedifferencesbetween
PythonandyourfavoriteprogramminglanguageIhavehighlightedmanysuchdifferences.Alittle
warningthough,Pythonissoongoingtobecomeyourfavoriteprogramminglanguage!

3.2.OfficialWebsite
Theofficialwebsiteofthebookishttp://swaroopch.com/notes/pythonwhereyoucanreadthewhole
bookonline,downloadthelatestversionsofthebook,buyaprintedhardcopy
(http://swaroopch.com/buybook)andalsosendmefeedback.

3.3.SomethingToThinkAbout

There are two ways of constructing a software design: one way is to make it so
simple that there are obviously no deficiencies the other is to make it so
complicatedthattherearenoobviousdeficiencies.
C.A.R.Hoare

Success in life is a matter not so much of talent and opportunity as of


concentrationandperseverance.
C.W.Wendte

http://www.swaroopch.com/notes/python/

17/165

1/4/2015

AByteofPython

4.Introduction
Pythonisoneofthoserarelanguageswhichcanclaimtobebothsimpleandpowerful.Youwillfind
yourselfpleasantlysurprisedtoseehoweasyitistoconcentrateonthesolutiontotheproblemrather
thanthesyntaxandstructureofthelanguageyouareprogrammingin.
TheofficialintroductiontoPythonis:

Python isan easy tolearn, powerful programminglanguage. It hasefficient high


level data structures and a simple but effective approach to objectoriented
programming. Pythons elegant syntax and dynamic typing, together with its
interpreted nature, make it an ideal language for scripting and rapid application
developmentinmanyareasonmostplatforms.

Iwilldiscussmostofthesefeaturesinmoredetailinthenextsection.

Storybehindthename
GuidovanRossum,thecreatorofthePythonlanguage,namedthelanguageaftertheBBCshow
"MontyPythonsFlyingCircus".Hedoesntparticularlylikesnakesthatkillanimalsforfoodby
windingtheirlongbodiesaroundthemandcrushingthem.

4.1.FeaturesofPython
Simple
Pythonisasimpleandminimalisticlanguage.ReadingagoodPythonprogramfeelsalmostlike
readingEnglish,althoughverystrictEnglish!ThispseudocodenatureofPythonisoneofitsgreatest
strengths.Itallowsyoutoconcentrateonthesolutiontotheproblemratherthanthelanguageitself.
EasytoLearn
Asyouwillsee,Pythonisextremelyeasytogetstartedwith.Pythonhasanextraordinarilysimple
syntax,asalreadymentioned.
FreeandOpenSource
PythonisanexampleofaFLOSS(Free/LibrandOpenSourceSoftware).Insimpleterms,youcan
freelydistributecopiesofthissoftware,readitssourcecode,makechangestoit,andusepiecesofitin
newfreeprograms.FLOSSisbasedontheconceptofacommunitywhichsharesknowledge.Thisis
http://www.swaroopch.com/notes/python/

18/165

1/4/2015

AByteofPython

oneofthereasonswhyPythonissogoodithasbeencreatedandisconstantlyimprovedbya
communitywhojustwanttoseeabetterPython.
HighlevelLanguage
WhenyouwriteprogramsinPython,youneverneedtobotheraboutthelowleveldetailssuchas
managingthememoryusedbyyourprogram,etc.
Portable
Duetoitsopensourcenature,Pythonhasbeenportedto(i.e.changedtomakeitworkon)many
platforms.AllyourPythonprogramscanworkonanyoftheseplatformswithoutrequiringany
changesatallifyouarecarefulenoughtoavoidanysystemdependentfeatures.
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!
YoucanevenuseaplatformlikeKivy (http://kivy.org)tocreategamesforyourcomputerandfor
iPhone,iPad,andAndroid.
Interpreted
Thisrequiresabitofexplanation.
AprogramwritteninacompiledlanguagelikeCorC[]+isconvertedfromthesourcelanguagei.e.C
orC+intoalanguagethatisspokenbyyourcomputer(binarycodei.e.0sand1s)usingacompiler
withvariousflagsandoptions.Whenyouruntheprogram,thelinker/loadersoftwarecopiesthe
programfromharddisktomemoryandstartsrunningit.
Python,ontheotherhand,doesnotneedcompilationtobinary.Youjustruntheprogramdirectlyfrom
thesourcecode.Internally,Pythonconvertsthesourcecodeintoanintermediateformcalled
bytecodesandthentranslatesthisintothenativelanguageofyourcomputerandthenrunsit.Allthis,
actually,makesusingPythonmucheasiersinceyoudonthavetoworryaboutcompilingtheprogram,
makingsurethattheproperlibrariesarelinkedandloaded,etc.ThisalsomakesyourPythonprograms
muchmoreportable,sinceyoucanjustcopyyourPythonprogramontoanothercomputeranditjust
works!
ObjectOriented
Pythonsupportsprocedureorientedprogrammingaswellasobjectorientedprogramming.In
procedureorientedlanguages,theprogramisbuiltaroundproceduresorfunctionswhicharenothing
butreusablepiecesofprograms.Inobjectorientedlanguages,theprogramisbuiltaroundobjects
http://www.swaroopch.com/notes/python/

19/165

1/4/2015

AByteofPython

whichcombinedataandfunctionality.PythonhasaverypowerfulbutsimplisticwayofdoingOOP,
especiallywhencomparedtobiglanguageslikeC++orJava.
Extensible
Ifyouneedacriticalpieceofcodetorunveryfastorwanttohavesomepieceofalgorithmnottobe
open,youcancodethatpartofyourprograminCorC\++andthenuseitfromyourPythonprogram.
Embeddable
YoucanembedPythonwithinyourC/C\++programstogivescriptingcapabilitiesforyourprograms
users.
ExtensiveLibraries
ThePythonStandardLibraryishugeindeed.Itcanhelpyoudovariousthingsinvolvingregular
expressions,documentationgeneration,unittesting,threading,databases,webbrowsers,CGI,FTP,
email,XML,XMLRPC,HTML,WAVfiles,cryptography,GUI(graphicaluserinterfaces),andother
systemdependentstuff.Remember,allthisisalwaysavailablewhereverPythonisinstalled.Thisis
calledtheBatteriesIncludedphilosophyofPython.
Besidesthestandardlibrary,therearevariousotherhighqualitylibrarieswhichyoucanfindatthe
PythonPackageIndex (http://pypi.python.org/pypi).
Summary
Pythonisindeedanexcitingandpowerfullanguage.Ithastherightcombinationofperformanceand
featuresthatmakewritingprogramsinPythonbothfunandeasy.

4.2.Python2versus3
Youcanignorethissectionifyourenotinterestedinthedifferencebetween"Pythonversion2"and
"Pythonversion3".Butpleasedobeawareofwhichversionyouareusing.Thisbookiswrittenfor
Python2.
Rememberthatonceyouhaveproperlyunderstoodandlearntouseoneversion,youcaneasilylearnthe
differencesandusetheotherone.Thehardpartislearningprogrammingandunderstandingthebasicsof
Pythonlanguageitself.Thatisourgoalinthisbook,andonceyouhaveachievedthatgoal,youcan
easilyusePython2orPython3dependingonyoursituation.
FordetailsondifferencesbetweenPython2andPython3,see:
ThefutureofPython2 (http://lwn.net/Articles/547191/)

http://www.swaroopch.com/notes/python/

20/165

1/4/2015

AByteofPython

Python/3pageontheUbuntuwiki (https://wiki.ubuntu.com/Python/3)

4.3.WhatProgrammersSay
YoumayfinditinterestingtoreadwhatgreathackerslikeESRhavetosayaboutPython:
1. EricS.Raymondistheauthorof"TheCathedralandtheBazaar"andisalsothepersonwhocoined
thetermOpenSource.HesaysthatPythonhasbecomehisfavoriteprogramminglanguage
(http://www.python.org/about/success/esr/).Thisarticlewastherealinspirationformyfirstbrushwith

Python.
2. BruceEckelistheauthorofthefamous'ThinkinginJava'and'ThinkinginC++'books.Hesaysthat
nolanguagehasmadehimmoreproductivethanPython.HesaysthatPythonisperhapstheonly
languagethatfocusesonmakingthingseasierfortheprogrammer.Readthecompleteinterview
(http://www.artima.com/intv/aboutme.html)formoredetails.

3. PeterNorvigisawellknownLispauthorandDirectorofSearchQualityatGoogle(thankstoGuido
vanRossumforpointingthatout).HesaysthatwritingPythonislikewritinginpseudocode
(https://news.ycombinator.com/item?id=1803815).HesaysthatPythonhasalwaysbeenanintegralpartof

Google.YoucanactuallyverifythisstatementbylookingattheGoogleJobs
(http://www.google.com/jobs/index.html)pagewhichlistsPythonknowledgeasarequirementfor

softwareengineers.

http://www.swaroopch.com/notes/python/

21/165

1/4/2015

AByteofPython

5.Installation
Whenwereferto"Python2"inthisbook,wewillbereferringtoanyversionofPythonequaltoor
greaterthanversion2.7 (https://www.python.org/downloads/).

5.1.InstallationonWindows
Visithttps://www.python.org/downloads/anddownloadthelatestversion.Theinstallationisjustlikeany
otherWindowsbasedsoftware.

CAUTION

Whenyouaregiventheoptionofuncheckingany"optional"components,dont
uncheckany.

5.1.1.DOSPrompt
IfyouwanttobeabletousePythonfromtheWindowscommandlinei.e.theDOSprompt,thenyou
needtosetthePATHvariableappropriately.
ForWindows2000,XP,2003,clickonControlPanelSystemAdvancedEnvironment
Variables.ClickonthevariablenamedPATHintheSystemVariablessection,thenselectEditandadd
;C:\Python27 (pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)to

theendofwhatisalreadythere.Ofcourse,usetheappropriatedirectoryname.
ForolderversionsofWindows,openthefile C:\AUTOEXEC.BAT andaddtheline
PATH=%PATH%;C:\Python33 andrestartthesystem.ForWindowsNT,usetheAUTOEXEC.NTfile.

ForWindowsVista:
1. ClickStartandchooseControlPanel
2. ClickSystem,ontherightyoullsee"Viewbasicinformationaboutyourcomputer"
3. Ontheleftisalistoftasks,thelastofwhichisAdvancedsystemsettings.Clickthat.
4. TheAdvancedtaboftheSystemPropertiesdialogboxisshown.ClicktheEnvironmentVariables
buttononthebottomright.
5. InthelowerboxtitledSystemVariablesscrolldowntoPathandclicktheEditbutton.
6. Changeyourpathasneedbe.
7. Restartyoursystem.VistadidntpickupthesystempathenvironmentvariablechangeuntilI
restarted.

http://www.swaroopch.com/notes/python/

22/165

1/4/2015

AByteofPython

ForWindows7and8:
1. RightclickonComputerfromyourdesktopandselectPropertiesorclickStartandchooseControl
PanelSystemandSecuritySystem.ClickonAdvancedsystemsettingsontheleftandthen
clickontheAdvancedtab.AtthebottomclickonEnvironmentVariablesandunderSystem
variables,lookforthePATHvariable,selectandthenpressEdit.
2. GototheendofthelineunderVariablevalueandappend ;C:\Python27 (pleaseverifythatthis
folderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Of
course,usetheappropriatefoldername.
3. Ifthevaluewas %SystemRoot%\system32; Itwillnowbecome
%SystemRoot%\system32;C:\Python27

4. ClickOKandyouaredone.Norestartisrequired,howeveryoumayhavetocloseandreopenthe
commandline.

5.1.2.RunningPythonpromptonWindows
ForWindowsusers,youcanruntheinterpreterinthecommandlineifyouhavesetthe PATH variable
appropriately.
ToopentheterminalinWindows,clickthestartbuttonandclickRun.Inthedialogbox,typecmdand
press

enter

key.

Then,typepythonandensuretherearenoerrors.

5.2.InstallationonMacOSX
ForMacOSXusers,Pythonmustbeinstalledalready.
Toverify,opentheterminalbypressing
andpress

enter

Command

Space

keys(toopenSpotlightsearch),typeTerminal

key.Now,runpythonandensuretherearenoerrors.

5.3.InstallationonGNU/Linux
ForGNU/Linuxusers,Pythonmustbeinstalledalready.
Toverify,opentheterminalbyopeningtheTerminalapplicationorbypressing

Alt

F2

andentering

gnometerminal.Ifthatdoesntwork,pleasereferthedocumentationofyourparticularGNU/Linux
distribution.Now,runpythonandensuretherearenoerrors.
YoucanseetheversionofPythononthescreenbyrunning:
http://www.swaroopch.com/notes/python/

23/165

1/4/2015

AByteofPython

$pythonV
Python2.7.6

$ isthepromptoftheshell.Itwillbedifferentforyoudependingonthesettingsof

NOTE

theoperatingsystemonyourcomputer,henceIwillindicatethepromptbyjustthe $
symbol.

CAUTION

Outputmaybedifferentonyourcomputer,dependingontheversionofPython
softwareinstalledonyourcomputer.

5.4.Summary
Fromnowon,wewillassumethatyouhavePythoninstalledonyoursystem.
Next,wewillwriteourfirstPythonprogram.

http://www.swaroopch.com/notes/python/

24/165

1/4/2015

AByteofPython

6.FirstSteps
Wewillnowseehowtorunatraditional'HelloWorld'programinPython.Thiswillteachyouhowto
write,saveandrunPythonprograms.
TherearetwowaysofusingPythontorunyourprogramusingtheinteractiveinterpreterpromptor
usingasourcefile.Wewillnowseehowtousebothofthesemethods.

6.1.UsingTheInterpreterPrompt
Opentheterminalinyouroperatingsystem(asdiscussedpreviouslyintheInstallationchapter)andthen
openthePythonpromptbytypingpythonandpressing

enter

key.

OnceyouhavestartedPython,youshouldsee >>> whereyoucanstarttypingstuff.Thisiscalledthe


Pythoninterpreterprompt.
AtthePythoninterpreterprompt,type:
print"HelloWorld"

followedbythe

enter

PYTHON

key.YoushouldseethewordsHelloWorldprintedtothescreen.

Hereisanexampleofwhatyoushouldbeseeing,whenusingaMacOSXcomputer.Thedetailsabout
thePythonsoftwarewilldifferbasedonyourcomputer,butthepartfromtheprompt(i.e.from >>>
onwards)shouldbethesameregardlessoftheoperatingsystem.
$python
Python2.7.6(default,Feb232014,16:08:15)
[GCC4.2.1CompatibleAppleLLVM5.0(clang500.2.79)]ondarwin
Type"help","copyright","credits"or"license"formoreinformation.
>>>print"helloworld"
helloworld
>>>

NoticethatPythongivesyoutheoutputofthelineimmediately!WhatyoujustenteredisasinglePython
statement.Weuseprintto(unsurprisingly)printanyvaluethatyousupplytoit.Here,wearesupplying
thetexthelloworldandthisispromptlyprintedtothescreen.
HowtoQuittheInterpreterPrompt

http://www.swaroopch.com/notes/python/

25/165

1/4/2015

AByteofPython

IfyouareusingaGNU/LinuxorOSXshell,youcanexittheinterpreterpromptby
NOTE

pressing

ctrl

followedbythe

orenteringexit()(note:remembertoincludetheparentheses,())

enter

key.

IfyouareusingtheWindowscommandprompt,press
enter

ctrl

followedbythe

key.

6.2.ChoosingAnEditor
Wecannottypeoutourprogramattheinterpreterprompteverytimewewanttorunsomething,sowe
havetosavetheminfilesandcanrunourprogramsanynumberoftimes.
TocreateourPythonsourcefiles,weneedaneditorsoftwarewhereyoucantypeandsave.Agood
programmerseditorwillmakeyourlifeeasierinwritingthesourcefiles.Hence,thechoiceofaneditor
iscrucialindeed.Youhavetochooseaneditorasyouwouldchooseacaryouwouldbuy.Agoodeditor
willhelpyouwritePythonprogramseasily,makingyourjourneymorecomfortableandhelpsyoureach
yourdestination(achieveyourgoal)inamuchfasterandsaferway.
OneoftheverybasicrequirementsissyntaxhighlightingwhereallthedifferentpartsofyourPython
programarecolorizedsothatyoucanseeyourprogramandvisualizeitsrunning.
Ifyouhavenoideawheretostart,IwouldrecommendusingPyCharmEducationalEdition
(https://www.jetbrains.com/pycharmeducational/)softwarewhichisavailableonWindows,MacOSXand

GNU/Linux.Detailsinthenextsection.
IfyouareusingWindows,donotuseNotepaditisabadchoicebecauseitdoesnotdosyntax
highlightingandalsoimportantlyitdoesnotsupportindentationofthetextwhichisveryimportantin
ourcaseaswewillseelater.Goodeditorswillautomaticallydothis.
Ifyouareanexperiencedprogrammer,thenyoumustbealreadyusingVim (http://www.vim.org)orEmacs
(http://www.gnu.org/software/emacs/).Needlesstosay,thesearetwoofthemostpowerfuleditorsandyou

willbenefitfromusingthemtowriteyourPythonprograms.Ipersonallyusebothformostofmy
programs,andhaveevenwrittenanentirebookonVim (http://swaroopch.com/notes/vim).
IncaseyouarewillingtotakethetimetolearnVimorEmacs,thenIhighlyrecommendthatyoudolearn
touseeitherofthemasitwillbeveryusefulforyouinthelongrun.However,asImentionedbefore,
beginnerscanstartwithPyCharmandfocusthelearningonPythonratherthantheeditoratthismoment.
Toreiterate,pleasechooseapropereditoritcanmakewritingPythonprogramsmorefunandeasy.

http://www.swaroopch.com/notes/python/

26/165

1/4/2015

AByteofPython

6.3.PyCharm
PyCharmEducationalEdition (https://www.jetbrains.com/pycharmeducational/)isafreeeditorwhichyoucan
useforwritingPythonprograms.
WhenyouopenPyCharm,youllseethis,clickonCreateNewProject:

SelectPurePython:

http://www.swaroopch.com/notes/python/

27/165

1/4/2015

AByteofPython

Changeuntitledtohelloworldasthelocationoftheproject,youshouldseedetailssimilartothis:

ClicktheCreatebutton.
RightclickonthehelloworldinthesidebarandselectNewPythonFile:

http://www.swaroopch.com/notes/python/

28/165

1/4/2015

AByteofPython

PyCharm>New>PythonFile

Youwillbeaskedtotypethename,typehello:

http://www.swaroopch.com/notes/python/

29/165

1/4/2015

AByteofPython

PyCharmNewFiledialogbox

Youcannowseeafileopenedforyou:

http://www.swaroopch.com/notes/python/

30/165

1/4/2015

AByteofPython

PyCharmhello.pyfile

Deletethelinesthatarealreadypresent,andnowtypethefollowing:
print"helloworld"

PYTHON

Nowrightclickonwhatyoutyped(withoutselectingthetext),andclickonRun'hello'.

http://www.swaroopch.com/notes/python/

31/165

1/4/2015

AByteofPython

PyCharmRun'hello'

Youshouldnowseetheoutput(whatitprints)ofyourprogram:

http://www.swaroopch.com/notes/python/

32/165

1/4/2015

AByteofPython

PyCharmoutput

Phew!Thatwasquiteafewstepstogetstarted,buthenceforth,everytimeweaskyoutocreateanew
file,remembertojustrightclickonhelloworldontheleftNewPythonFileandcontinuethesame
stepstotypeandrunasshownabove.
YoucanfindmoreinformationaboutPyCharminthePyCharmQuickstart
(https://www.jetbrains.com/pycharmeducational/quickstart/)page.

6.4.Vim
1. InstallVim (http://www.vim.org)
a. MacOSXusersshouldinstallmacvimpackageviaHomeBrew (http://brew.sh/)
http://www.swaroopch.com/notes/python/

33/165

1/4/2015

AByteofPython

b. Windowsusersshoulddownloadthe"selfinstallingexecutable"from
http://www.vim.org/download.php
c. GNU/LinuxusersshouldgetVimfromtheirdistributionssoftwarerepositories,e.g.Debianand
Ubuntuuserscaninstallthevim (http://packages.ubuntu.com/saucy/vim)package.
2. ReadtheVimasPythonIDE (http://blog.sontek.net/blog/detail/turningvimintoamodernpythonide)article
byJohnMAnderson.
3. Installjedivim (https://github.com/davidhalter/jedivim)pluginforautocompletion.

6.5.Emacs
1. InstallEmacs24 (http://www.gnu.org/software/emacs/).
a. MacOSXusersshouldgetEmacsfromhttp://emacsformacosx.com
b. WindowsusersshouldgetEmacsfromhttp://ftp.gnu.org/gnu/emacs/windows/
c. GNU/LinuxusersshouldgetEmacsfromtheirdistributionssoftwarerepositories,e.g.Debian
andUbuntuuserscaninstalltheemacs24 (http://packages.ubuntu.com/saucy/emacs24)package.
2. InstallELPY (https://github.com/jorgenschaefer/elpy/wiki).

6.6.UsingASourceFile
Nowletsgetbacktoprogramming.Thereisatraditionthatwheneveryoulearnanewprogramming
language,thefirstprogramthatyouwriteandrunisthe'HelloWorld'programallitdoesisjustsay
'HelloWorld'whenyourunit.AsSimonCozens[1]says,itisthe"traditionalincantationtothe
programminggodstohelpyoulearnthelanguagebetter."
Startyourchoiceofeditor,enterthefollowingprogramandsaveitashello.py.
IfyouareusingPyCharm,wehavealreadydiscussedhowtorunfromasourcefile.
Forothereditors,openanewfilehello.pyandtypethis:
print"helloworld"

PYTHON

Whereshouldyousavethefile?Toanyfolderforwhichyouknowthelocationofthefolder.Ifyoudont
understandwhatthatmeans,createanewfolderandusethatlocationtosaveandrunallyourPython
programs:
/tmp/py onMacOSX
http://www.swaroopch.com/notes/python/

34/165

1/4/2015

AByteofPython

/tmp/py onGNU/Linux
C:\\py onWindows

Tocreatetheabovefolder(fortheoperatingsystemyouareusing),usethemkdircommandinthe
terminal,forexample,mkdir/tmp/py.
IMPORTANT

Alwaysensurethatyougiveitthefileextensionof.py,forexample,foo.py.

TorunyourPythonprogram:
1. Openaterminalwindow(seethepreviousInstallationchapteronhowtodothat)
2. Changedirectorytowhereyousavedthefile,forexample,cd/tmp/py
3. Runtheprogrambyenteringthecommandpythonhello.py.Theoutputisasshownbelow.
$pythonhello.py
helloworld

http://www.swaroopch.com/notes/python/

35/165

1/4/2015

AByteofPython

Screenshotofrunningprograminterminal

Ifyougottheoutputasshownabove,congratulations!youhavesuccessfullyrunyourfirstPython
program.Youhavesuccessfullycrossedthehardestpartoflearningprogramming,whichis,getting
startedwithyourfirstprogram!
Incaseyougotanerror,pleasetypetheaboveprogramexactlyasshownaboveandruntheprogram
again.NotethatPythoniscasesensitivei.e.printisnotthesameasPrintnotethelowercasepinthe
formerandtheuppercasePinthelatter.Also,ensuretherearenospacesortabsbeforethefirstcharacter
ineachlinewewillseewhythisisimportantlater.
HowItWorks
APythonprogramiscomposedofstatements.Inourfirstprogram,wehaveonlyonestatement.Inthis
statement,wecalltheprintstatementtowhichwesupplythetext"helloworld".

6.7.GettingHelp
http://www.swaroopch.com/notes/python/

36/165

1/4/2015

AByteofPython

IfyouneedquickinformationaboutanyfunctionorstatementinPython,thenyoucanusethebuiltin
helpfunctionality.Thisisveryusefulespeciallywhenusingtheinterpreterprompt.Forexample,run
help('len') thisdisplaysthehelpforthelenfunctionwhichisusedtocountnumberofitems.

TIP

Pressqtoexitthehelp.

Similarly,youcanobtaininformationaboutalmostanythinginPython.Usehelp()tolearnmoreabout
usinghelpitself!
Incaseyouneedtogethelpforoperatorslikereturn,thenyouneedtoputthoseinsidequotessuchas
help('return') sothatPythondoesntgetconfusedonwhatweretryingtodo.

6.8.Summary
Youshouldnowbeabletowrite,saveandrunPythonprogramsatease.
NowthatyouareaPythonuser,letslearnsomemorePythonconcepts.

http://www.swaroopch.com/notes/python/

37/165

1/4/2015

AByteofPython

7.Basics
Justprintinghelloworldisnotenough,isit?Youwanttodomorethanthatyouwanttotakesome
input,manipulateitandgetsomethingoutofit.WecanachievethisinPythonusingconstantsand
variables,andwelllearnsomeotherconceptsaswellinthischapter.

7.1.Comments
Commentsareanytexttotherightofthe # symbolandismainlyusefulasnotesforthereaderofthe
program.
Forexample:
print'helloworld'#Notethatprintisastatement

PYTHON

or:
#Notethatprintisastatement
print'helloworld'

PYTHON

Useasmanyusefulcommentsasyoucaninyourprogramto:
explainassumptions
explainimportantdecisions
explainimportantdetails
explainproblemsyouretryingtosolve
explainproblemsyouretryingtoovercomeinyourprogram,etc.
Codetellsyouhow,commentsshouldtellyouwhy
(http://www.codinghorror.com/blog/2006/12/codetellsyouhowcommentstellyouwhy.html).

Thisisusefulforreadersofyourprogramsothattheycaneasilyunderstandwhattheprogramisdoing.
Remember,thatpersoncanbeyourselfaftersixmonths!

7.2.LiteralConstants
Anexampleofaliteralconstantisanumberlike 5 , 1.23 ,orastringlike 'Thisisastring' or
"Itsastring!" .
http://www.swaroopch.com/notes/python/

38/165

1/4/2015

AByteofPython

Itiscalledaliteralbecauseitisliteralyouuseitsvalueliterally.Thenumber 2 alwaysrepresentsitself
andnothingelseitisaconstantbecauseitsvaluecannotbechanged.Hence,allthesearereferredtoas
literalconstants.

7.3.Numbers
Numbersaremainlyoftwotypesintegersandfloats.
Anexamplesofanintegeris 2 whichisjustawholenumber.
Examplesoffloatingpointnumbers(orfloatsforshort)are 3.23 and 52.3E4 .TheEnotation
indicatespowersof10.Inthiscase, 52.3E4 means52.3*10^4^.

NOTE

NoteforExperiencedProgrammers
Thereisnoseparatelongtype.Theinttypecanbeanintegerofanysize.

7.4.Strings
Astringisasequenceofcharacters.Stringsarebasicallyjustabunchofwords.
YouwillbeusingstringsinalmosteveryPythonprogramthatyouwrite,sopayattentiontothefollowing
part.

7.4.1.SingleQuote
Youcanspecifystringsusingsinglequotessuchas 'Quotemeonthis' .
Allwhitespacei.e.spacesandtabs,withinthequotes,arepreservedasis.

7.4.2.DoubleQuotes
Stringsindoublequotesworkexactlythesamewayasstringsinsinglequotes.Anexampleis "Whats
yourname?" .

7.4.3.TripleQuotes
Youcanspecifymultilinestringsusingtriplequotes( """ or ''' ).Youcanusesinglequotesand
doublequotesfreelywithinthetriplequotes.Anexampleis:

http://www.swaroopch.com/notes/python/

39/165

1/4/2015

AByteofPython

'''Thisisamultilinestring.Thisisthefirstline.
Thisisthesecondline.
"What'syourname?,"Iasked.
Hesaid"Bond,JamesBond."
'''

PYTHON

7.4.4.StringsAreImmutable
Thismeansthatonceyouhavecreatedastring,youcannotchangeit.Althoughthismightseemlikea
badthing,itreallyisnt.Wewillseewhythisisnotalimitationinthevariousprogramsthatweseelater
on.
NoteforC/C++Programmers
NOTE

ThereisnoseparatechardatatypeinPython.ThereisnorealneedforitandIamsure
youwontmissit.

NoteforPerl/PHPProgrammers
NOTE

Rememberthatsinglequotedstringsanddoublequotedstringsarethesametheydo
notdifferinanyway.

7.4.5.Theformatmethod
Sometimeswemaywanttoconstructstringsfromotherinformation.Thisiswheretheformat()method
isuseful.
Savethefollowinglinesasafilestr_format.py:
age=20
name='Swaroop'

PYTHON

print'{0}was{1}yearsoldwhenhewrotethisbook'.format(name,age)
print'Whyis{0}playingwiththatpython?'.format(name)

Output:
$pythonstr_format.py
Swaroopwas20yearsoldwhenhewrotethisbook
WhyisSwaroopplayingwiththatpython?

HowItWorks
http://www.swaroopch.com/notes/python/

40/165

1/4/2015

AByteofPython

Astringcanusecertainspecificationsandsubsequently,theformatmethodcanbecalledtosubstitute
thosespecificationswithcorrespondingargumentstotheformatmethod.
Observethefirstusagewhereweuse{0}andthiscorrespondstothevariablenamewhichisthefirst
argumenttotheformatmethod.Similarly,thesecondspecificationis{1}correspondingtoagewhichis
thesecondargumenttotheformatmethod.NotethatPythonstartscountingfrom0whichmeansthat
firstpositionisatindex0,secondpositionisatindex1,andsoon.
Noticethatwecouldhaveachievedthesameusingstringconcatenation:
name+'is'+str(age)+'yearsold'

PYTHON

butthatismuchuglieranderrorprone.Second,theconversiontostringwouldbedoneautomaticallyby
theformatmethodinsteadoftheexplicitconversiontostringsneededinthiscase.Third,whenusingthe
formatmethod,wecanchangethemessagewithouthavingtodealwiththevariablesusedandvice
versa.
Alsonotethatthenumbersareoptional,soyoucouldhavealsowrittenas:
age=20
name='Swaroop'

PYTHON

print'{}was{}yearsoldwhenhewrotethisbook'.format(name,age)
print'Whyis{}playingwiththatpython?'.format(name)

whichwillgivethesameexactoutputasthepreviousprogram.
WhatPythondoesintheformatmethodisthatitsubstituteseachargumentvalueintotheplaceofthe
specification.Therecanbemoredetailedspecificationssuchas:
#decimal(.)precisionof3forfloat'0.333'
print'{0:.3f}'.format(1.0/3)
#fillwithunderscores(_)withthetextcentered
#(^)to11width'___hello___'
print'{0:_^11}'.format('hello')
#keywordbased'SwaroopwroteAByteofPython'
print'{name}wrote{book}'.format(name='Swaroop',
book='AByteofPython')

PYTHON

Output:

http://www.swaroopch.com/notes/python/

41/165

1/4/2015

AByteofPython

0.333
___hello___
SwaroopwroteAByteofPython

Sincewearediscussingformatting,notethatprintalwaysendswithaninvisible"newline"character(\n)
sothatrepeatedcallstoprintwillallprintonaseparatelineeach.Topreventthisnewlinecharacterfrom
beingprinted,youcanendthestatementwithacomma:
print"a",
print"b",

PYTHON

Outputis:
ab

7.4.6.EscapeSequences
Suppose,youwanttohaveastringwhichcontainsasinglequote( ' ),howwillyouspecifythisstring?
Forexample,thestringis "Whatsyourname?" .Youcannotspecify 'Whatsyourname?'
becausePythonwillbeconfusedastowherethestringstartsandends.So,youwillhavetospecifythat
thissinglequotedoesnotindicatetheendofthestring.Thiscanbedonewiththehelpofwhatiscalled
anescapesequence.Youspecifythesinglequoteas \' :noticethebackslash.Now,youcanspecifythe
stringas 'What'syourname?' .
Anotherwayofspecifyingthisspecificstringwouldbe "Whatsyourname?" i.e.usingdouble
quotes.Similarly,youhavetouseanescapesequenceforusingadoublequoteitselfinadoublequoted
string.Also,youhavetoindicatethebackslashitselfusingtheescapesequence \\ .
Whatifyouwantedtospecifyatwolinestring?Onewayistouseatriplequotedstringasshown
previouslyoryoucanuseanescapesequenceforthenewlinecharacter\ntoindicatethestartofanew
line.Anexampleis:
'Thisisthefirstline\nThisisthesecondline'

PYTHON

Anotherusefulescapesequencetoknowisthetab:\t.TherearemanymoreescapesequencesbutIhave
mentionedonlythemostusefuloneshere.
Onethingtonoteisthatinastring,asinglebackslashattheendofthelineindicatesthatthestringis
continuedinthenextline,butnonewlineisadded.Forexample:
http://www.swaroopch.com/notes/python/

42/165

1/4/2015

AByteofPython

"Thisisthefirstsentence.\
Thisisthesecondsentence."

PYTHON

isequivalentto
"Thisisthefirstsentence.Thisisthesecondsentence."

PYTHON

7.4.7.RawString
Ifyouneedtospecifysomestringswherenospecialprocessingsuchasescapesequencesarehandled,
thenwhatyouneedistospecifyarawstringbyprefixingrorRtothestring.Anexampleis:
r"Newlinesareindicatedby\n"

PYTHON

NoteforRegularExpressionUsers
NOTE

Alwaysuserawstringswhendealingwithregularexpressions.Otherwise,alotof
backwhackingmayberequired.Forexample,backreferencescanbereferredtoas
'\\1' or r'\1' .

7.5.Variable
Usingjustliteralconstantscansoonbecomeboringweneedsomewayofstoringanyinformationand
manipulatethemaswell.Thisiswherevariablescomeintothepicture.Variablesareexactlywhatthe
nameimpliestheirvaluecanvary,i.e.,youcanstoreanythingusingavariable.Variablesarejustparts
ofyourcomputersmemorywhereyoustoresomeinformation.Unlikeliteralconstants,youneedsome
methodofaccessingthesevariablesandhenceyougivethemnames.

7.6.IdentifierNaming
Variablesareexamplesofidentifiers.Identifiersarenamesgiventoidentifysomething.Therearesome
rulesyouhavetofollowfornamingidentifiers:
Thefirstcharacteroftheidentifiermustbealetterofthealphabet(uppercaseASCIIorlowercase
ASCIIorUnicodecharacter)oranunderscore( _ ).
Therestoftheidentifiernamecanconsistofletters(uppercaseASCIIorlowercaseASCIIorUnicode
character),underscores( _ )ordigits(09).
Identifiernamesarecasesensitive.Forexample, myname and myName arenotthesame.Notethe
lowercase n intheformerandtheuppercase N inthelatter.
http://www.swaroopch.com/notes/python/

43/165

1/4/2015

AByteofPython

Examplesofvalididentifiernamesare i , name_2_3 .Examplesofinvalididentifiernamesare


2things , thisisspacedout , myname and >a1b2_c3 .

7.7.DataTypes
Variablescanholdvaluesofdifferenttypescalleddatatypes.Thebasictypesarenumbersandstrings,
whichwehavealreadydiscussed.Inlaterchapters,wewillseehowtocreateourowntypesusing
classes.

7.8.Object
Remember,Pythonreferstoanythingusedinaprogramasanobject.Thisismeantinthegenericsense.
Insteadofsaying"thesomething"',wesay"theobject".
NoteforObjectOrientedProgrammingusers
NOTE

Pythonisstronglyobjectorientedinthesensethateverythingisanobjectincluding
numbers,stringsandfunctions.

Wewillnowseehowtousevariablesalongwithliteralconstants.Savethefollowingexampleandrun
theprogram.

7.9.HowtowritePythonprograms
Henceforth,thestandardproceduretosaveandrunaPythonprogramisasfollows:

7.10.ForPyCharm
1. OpenPyCharm.
2. Createnewfilewiththefilenamementioned.
3. Typetheprogramcodegivenintheexample.
4. Rightclickandrunthecurrentfile.
Wheneveryouhavetoprovidecommandlinearguments,clickonRunEdit
ConfigurationsandtypetheargumentsintheScriptparameters:sectionandclickthe
OKbutton:

http://www.swaroopch.com/notes/python/

44/165

1/4/2015

AByteofPython

PyCharmcommandlinearguments

NOTE

7.11.Forothereditors
1. Openyoureditorofchoice.
2. Typetheprogramcodegivenintheexample.
3. Saveitasafilewiththefilenamementioned.
4. Runtheinterpreterwiththecommandpythonprogram.pytoruntheprogram.

7.12.Example:UsingVariablesAndLiteralConstants
Typeandrunthefollowingprogram:

http://www.swaroopch.com/notes/python/

45/165

1/4/2015

AByteofPython

#Filename:var.py
i=5
printi
i=i+1
printi

PYTHON

s='''Thisisamultilinestring.
Thisisthesecondline.'''
prints

Output:
5
6
Thisisamultilinestring.
Thisisthesecondline.

HowItWorks
Hereshowthisprogramworks.First,weassigntheliteralconstantvalue5tothevariableiusingthe
assignmentoperator( = ).Thislineiscalledastatementbecauseitstatesthatsomethingshouldbedone
andinthiscase,weconnectthevariablenameitothevalue5.Next,weprintthevalueofiusingthe
printstatementwhich,unsurprisingly,justprintsthevalueofthevariabletothescreen.
Thenweadd1tothevaluestorediniandstoreitback.Wethenprintitandexpectedly,wegetthevalue
6.
Similarly,weassigntheliteralstringtothevariablesandthenprintit.
Noteforstaticlanguageprogrammers
NOTE

Variablesareusedbyjustassigningthemavalue.Nodeclarationordatatype
definitionisneeded/used.

7.13.LogicalAndPhysicalLine
Aphysicallineiswhatyouseewhenyouwritetheprogram.AlogicallineiswhatPythonseesasasingle
statement.Pythonimplicitlyassumesthateachphysicallinecorrespondstoalogicalline.
Anexampleofalogicallineisastatementlike print'helloworld' ifthiswasonalinebyitself
(asyouseeitinaneditor),thenthisalsocorrespondstoaphysicalline.
Implicitly,Pythonencouragestheuseofasinglestatementperlinewhichmakescodemorereadable.
http://www.swaroopch.com/notes/python/

46/165

1/4/2015

AByteofPython

Ifyouwanttospecifymorethanonelogicallineonasinglephysicalline,thenyouhavetoexplicitly
specifythisusingasemicolon( ; )whichindicatestheendofalogicalline/statement.Forexample:
i=5
printi

PYTHON

iseffectivelysameas
i=5;
printi;

PYTHON

whichisalsosameas
i=5;printi;

PYTHON

andsameas
i=5;printi

PYTHON

However,Istronglyrecommendthatyousticktowritingamaximumofasinglelogicallineoneach
singlephysicalline.Theideaisthatyoushouldneverusethesemicolon.Infact,Ihaveneverusedor
evenseenasemicoloninaPythonprogram.
Thereisonekindofsituationwherethisconceptisreallyuseful:ifyouhavealonglineofcode,youcan
breakitintomultiplephysicallinesbyusingthebackslash.Thisisreferredtoasexplicitlinejoining:
s='Thisisastring.\
Thiscontinuesthestring.'
prints

PYTHON

Output:
Thisisastring.Thiscontinuesthestring.

Similarly,

http://www.swaroopch.com/notes/python/

47/165

1/4/2015

AByteofPython

print\
i

PYTHON

isthesameas
printi

PYTHON

Sometimes,thereisanimplicitassumptionwhereyoudontneedtouseabackslash.Thisisthecase
wherethelogicallinehasastartingparentheses,startingsquarebracketsorastartingcurlybracesbutnot
anendingone.Thisiscalledimplicitlinejoining.Youcanseethisinactionwhenwewriteprograms
usinglistsinlaterchapters.

7.14.Indentation
WhitespaceisimportantinPython.Actually,whitespaceatthebeginningofthelineisimportant.
Thisiscalledindentation.Leadingwhitespace(spacesandtabs)atthebeginningofthelogicallineis
usedtodeterminetheindentationlevelofthelogicalline,whichinturnisusedtodeterminethegrouping
ofstatements.
Thismeansthatstatementswhichgotogethermusthavethesameindentation.Eachsuchsetof
statementsiscalledablock.Wewillseeexamplesofhowblocksareimportantinlaterchapters.
Onethingyoushouldrememberisthatwrongindentationcangiverisetoerrors.Forexample:
i=5
#Errorbelow!Noticeasinglespaceatthestartoftheline
print'Valueis',i
print'Irepeat,thevalueis',i

PYTHON

Whenyourunthis,yougetthefollowingerror:
File"whitespace.py",line5
print'Valueis',i
^
IndentationError:unexpectedindent

Noticethatthereisasinglespaceatthebeginningofthesecondline.TheerrorindicatedbyPythontells
usthatthesyntaxoftheprogramisinvalidi.e.theprogramwasnotproperlywritten.Whatthismeansto
youisthatyoucannotarbitrarilystartnewblocksofstatements(exceptforthedefaultmainblockwhich
http://www.swaroopch.com/notes/python/

48/165

1/4/2015

AByteofPython

youhavebeenusingallalong,ofcourse).Caseswhereyoucanusenewblockswillbedetailedinlater
chapterssuchastheControlFlow.
Howtoindent
Usefourspacesforindentation.ThisistheofficialPythonlanguagerecommendation.Goodeditorswill
automaticallydothisforyou.Makesureyouuseaconsistentnumberofspacesforindentation,otherwise
yourprogramwillshowerrors.
Notetostaticlanguageprogrammers
NOTE

Pythonwillalwaysuseindentationforblocksandwillneverusebraces.Run from
futureimportbraces tolearnmore.

7.15.Summary
Nowthatwehavegonethroughmanynittygrittydetails,wecanmoveontomoreinterestingstuffsuch
ascontrolflowstatements.Besuretobecomecomfortablewithwhatyouhavereadinthischapter.

http://www.swaroopch.com/notes/python/

49/165

1/4/2015

AByteofPython

8.OperatorsandExpressions
Moststatements(logicallines)thatyouwritewillcontainexpressions.Asimpleexampleofan
expressionis 2+3 .Anexpressioncanbebrokendownintooperatorsandoperands.
Operatorsarefunctionalitythatdosomethingandcanberepresentedbysymbolssuchas + orbyspecial
keywords.Operatorsrequiresomedatatooperateonandsuchdataiscalledoperands.Inthiscase, 2
and 3 aretheoperands.

8.1.Operators
Wewillbrieflytakealookattheoperatorsandtheirusage.
Notethatyoucanevaluatetheexpressionsgivenintheexamplesusingtheinterpreterinteractively.For
example,totesttheexpression 2+3 ,usetheinteractivePythoninterpreterprompt:
>>>2+3
5
>>>3*5
15
>>>

PYTHON

Hereisaquickoverviewoftheavailableoperators:
+ (plus)

Addstwoobjects
3+5 gives 8 . 'a'+'b' gives 'ab' .
(minus)

Givesthesubtractionofonenumberfromtheotherifthefirstoperandisabsentitisassumedtobe
zero.
5.2 givesanegativenumberand 5024 gives 26 .

*(multiply)
Givesthemultiplicationofthetwonumbersorreturnsthestringrepeatedthatmanytimes.
2*3 gives 6 . 'la'*3 gives 'lalala' .

**(power)
http://www.swaroopch.com/notes/python/

50/165

1/4/2015

AByteofPython

Returnsxtothepowerofy
3**4 gives 81 (i.e. 3*3*3*3 )
/ (divide)

Dividexbyy
13/3 gives 4 . 13.0/3 gives 4.333333333333333
% (modulo)

Returnstheremainderofthedivision
13%3 gives 1 . 25.5%2.25 gives 1.5 .
<< (leftshift)

Shiftsthebitsofthenumbertotheleftbythenumberofbitsspecified.(Eachnumberisrepresentedin
memorybybitsorbinarydigitsi.e.0and1)
2<<2 gives 8 . 2 isrepresentedby 10 inbits.

Leftshiftingby2bitsgives 1000 whichrepresentsthedecimal 8 .


>> (rightshift)

Shiftsthebitsofthenumbertotherightbythenumberofbitsspecified.
11>>1 gives 5 .
11 isrepresentedinbitsby 1011 whichwhenrightshiftedby1bitgives 101`whichisthe
decimal`5 .
& (bitwiseAND)

BitwiseANDofthenumbers
5&3 gives 1 .
| (bitwiseOR)

BitwiseORofthenumbers
5|3 gives 7

http://www.swaroopch.com/notes/python/

51/165

1/4/2015

AByteofPython

^ (bitwiseXOR)

BitwiseXORofthenumbers
5^3 gives 6
~ (bitwiseinvert)

Thebitwiseinversionofxis(x+1)
~5 gives 6 .Moredetailsathttp://stackoverflow.com/a/11810203
< (lessthan)

Returnswhetherxislessthany.Allcomparisonoperatorsreturn True or False .Notethe


capitalizationofthesenames.
5<3 gives False and 3<5 gives True .

Comparisonscanbechainedarbitrarily: 3<5<7 gives True .


> (greaterthan)

Returnswhetherxisgreaterthany
5>3 returns True .Ifbothoperandsarenumbers,theyarefirstconvertedtoacommontype.

Otherwise,italwaysreturns False .
(lessthanorequalto)

Returnswhetherxislessthanorequaltoy
x=3;y=6;xy returns True .
>= (greaterthanorequalto)

Returnswhetherxisgreaterthanorequaltoy
x=4;y=3;x>=3 returns True .
== (equalto)

Comparesiftheobjectsareequal
x=2;y=2;x==y returns True .
x='str';y='stR';x==y returns False .
http://www.swaroopch.com/notes/python/

52/165

1/4/2015

AByteofPython

x='str';y='str';x==y returns True .


!= (notequalto)

Comparesiftheobjectsarenotequal
x=2;y=3;x!=y returns True .
not (booleanNOT)

Ifxis True ,itreturns False .Ifxis False ,itreturns True .


x=True;notx returns False .
and (booleanAND)
xandy returns False ifxis False ,elseitreturnsevaluationofy
x=False;y=True;xandy returns False sincexisFalse.Inthiscase,Pythonwillnot

evaluateysinceitknowsthatthelefthandsideofthe'and'expressionis False whichimpliesthat


thewholeexpressionwillbe False irrespectiveoftheothervalues.Thisiscalledshortcircuit
evaluation.
or (booleanOR)

Ifxis True ,itreturnsTrue,elseitreturnsevaluationofy


x=True;y=False;xory returns True .Shortcircuitevaluationapplieshereaswell.

8.2.Shortcutformathoperationandassignment
Itiscommontorunamathoperationonavariableandthenassigntheresultoftheoperationbacktothe
variable,hencethereisashortcutforsuchexpressions:
a=2
a=a*3

PYTHON

canbewrittenas:
a=2
a*=3

PYTHON

Noticethat var=varoperationexpression becomes varoperation=expression .


http://www.swaroopch.com/notes/python/

53/165

1/4/2015

AByteofPython

8.3.EvaluationOrder
Ifyouhadanexpressionsuchas 2+3*4 ,istheadditiondonefirstorthemultiplication?Ourhigh
schoolmathstellsusthatthemultiplicationshouldbedonefirst.Thismeansthatthemultiplication
operatorhashigherprecedencethantheadditionoperator.
ThefollowingtablegivestheprecedencetableforPython,fromthelowestprecedence(leastbinding)to
thehighestprecedence(mostbinding).Thismeansthatinagivenexpression,Pythonwillfirstevaluate
theoperatorsandexpressionslowerinthetablebeforetheoneslistedhigherinthetable.
Thefollowingtable,takenfromthePythonreferencemanual
(http://docs.python.org/3/reference/expressions.html#operatorprecedence),isprovidedforthesakeof

completeness.Itisfarbettertouseparenthesestogroupoperatorsandoperandsappropriatelyinorderto
explicitlyspecifytheprecedence.Thismakestheprogrammorereadable.SeeChangingtheOrderof
Evaluationbelowfordetails.
lambda

LambdaExpression
ifelse

Conditionalexpression
or

BooleanOR
and

BooleanAND
notx

BooleanNOT
in,notin,is,isnot,<,,>,>=,!=,==

Comparisons,includingmembershiptestsandidentitytests
|

BitwiseOR
^

BitwiseXOR
http://www.swaroopch.com/notes/python/

54/165

1/4/2015

AByteofPython

&

BitwiseAND
<<,>>

Shifts
+,

Additionandsubtraction
*,/,//,%

Multiplication,Division,FloorDivisionandRemainder
+x,x,~x

Positive,Negative,bitwiseNOT
**

Exponentiation
x[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.

8.4.ChangingtheOrderOfEvaluation
Tomaketheexpressionsmorereadable,wecanuseparentheses.Forexample, 2+(3*4) isdefinitely
easiertounderstandthan 2+3*4 whichrequiresknowledgeoftheoperatorprecedences.Aswith
everythingelse,theparenthesesshouldbeusedreasonably(donotoverdoit)andshouldnotbe
redundant,asin (2+(3*4)) .
Thereisanadditionaladvantagetousingparenthesesithelpsustochangetheorderofevaluation.For
example,ifyouwantadditiontobeevaluatedbeforemultiplicationinanexpression,thenyoucanwrite
somethinglike (2+3)*4 .
http://www.swaroopch.com/notes/python/

55/165

1/4/2015

AByteofPython

8.5.Associativity
Operatorsareusuallyassociatedfromlefttoright.Thismeansthatoperatorswiththesameprecedence
areevaluatedinalefttorightmanner.Forexample, 2+3+4 isevaluatedas (2
3)+4 .Someoperatorslikeassignmentoperatorshaverighttoleftassociativityi.e. a=b=c is

treatedas a=(b=c) .

8.6.Expressions
Example(saveasexpression.py):
length=5
breadth=2

PYTHON

area=length*breadth
print'Areais',area
print'Perimeteris',2*(length+breadth)

Output:
$pythonexpression.py
Areais10
Perimeteris14

HowItWorks
Thelengthandbreadthoftherectanglearestoredinvariablesbythesamename.Weusetheseto
calculatetheareaandperimeteroftherectanglewiththehelpofexpressions.Westoretheresultofthe
expression length*breadth inthevariableareaandthenprintitusingtheprintfunction.Inthe
secondcase,wedirectlyusethevalueoftheexpression 2*(length+breadth) intheprint
statement.
Also,noticehowPythonprettyprintstheoutput.Eventhoughwehavenotspecifiedaspacebetween
'Areais' andthevariable area ,Pythonputsitforussothatwegetacleanniceoutputandthe

programismuchmorereadablethisway(sincewedontneedtoworryaboutspacinginthestringswe
useforoutput).ThisisanexampleofhowPythonmakeslifeeasyfortheprogrammer.

8.7.Summary
Wehaveseenhowtouseoperators,operandsandexpressionsthesearethebasicbuildingblocksofany
program.Next,wewillseehowtomakeuseoftheseinourprogramsusingstatements.

http://www.swaroopch.com/notes/python/

56/165

1/4/2015

AByteofPython

9.ControlFlow
Intheprogramswehaveseentillnow,therehasalwaysbeenaseriesofstatementsfaithfullyexecutedby
Pythoninexacttopdownorder.Whatifyouwantedtochangetheflowofhowitworks?Forexample,
youwanttheprogramtotakesomedecisionsanddodifferentthingsdependingondifferentsituations,
suchasprinting'GoodMorning'or'GoodEvening'dependingonthetimeoftheday?
Asyoumighthaveguessed,thisisachievedusingcontrolflowstatements.Therearethreecontrolflow
statementsinPythonif,forandwhile.

9.1.Theifstatement
Theifstatementisusedtocheckacondition:iftheconditionistrue,werunablockofstatements(called
theifblock),elseweprocessanotherblockofstatements(calledtheelseblock).Theelseclauseis
optional.
Example(saveasif.py):
number=23
guess=int(raw_input('Enteraninteger:'))

PYTHON

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:

http://www.swaroopch.com/notes/python/

57/165

1/4/2015

AByteofPython

$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.Wesetthe
variablenumbertoanyintegerwewant,say 23 .Then,wetaketheusersguessusingthe
raw_input() function.Functionsarejustreusablepiecesofprograms.Wellreadmoreaboutthemin

thenextchapter.
Wesupplyastringtothebuiltin raw_input functionwhichprintsittothescreenandwaitsforinput
fromtheuser.Onceweentersomethingandpress

enter

key,the raw_input() functionreturnswhat

weentered,asastring.Wethenconvertthisstringtoanintegerusing int andthenstoreitinthe


variable guess .Actually,the int isaclassbutallyouneedtoknowrightnowisthatyoucanuseitto
convertastringtoaninteger(assumingthestringcontainsavalidintegerinthetext).
Next,wecomparetheguessoftheuserwiththenumberwehavechosen.Iftheyareequal,weprinta
successmessage.NoticethatweuseindentationlevelstotellPythonwhichstatementsbelongtowhich
block.ThisiswhyindentationissoimportantinPython.Ihopeyouarestickingtothe"consistent
indentation"rule.Areyou?
Noticehowthe if statementcontainsacolonattheendweareindicatingtoPythonthatablockof
statementsfollows.
Then,wecheckiftheguessislessthanthenumber,andifso,weinformtheuserthattheymustguessa
littlehigherthanthat.Whatwehaveusedhereisthe elif clausewhichactuallycombinestworelated
ifelseifelse statementsintoonecombined ifelifelse statement.Thismakestheprogram

easierandreducestheamountofindentationrequired.

http://www.swaroopch.com/notes/python/

58/165

1/4/2015

AByteofPython

The elif and else statementsmustalsohaveacolonattheendofthelogicallinefollowedbytheir


correspondingblockofstatements(withproperindentation,ofcourse)
Youcanhaveanother if statementinsidetheifblockofan if statementandsoonthisiscalleda
nested if statement.
Rememberthatthe elif and else partsareoptional.Aminimalvalid if statementis:
ifTrue:
print'Yes,itistrue'

PYTHON

AfterPythonhasfinishedexecutingthecomplete if statementalongwiththeassociated elif and


else clauses,itmovesontothenextstatementintheblockcontainingthe if statement.Inthiscase,it

isthemainblock(whereexecutionoftheprogramstarts),andthenextstatementisthe print'Done'
statement.Afterthis,Pythonseestheendsoftheprogramandsimplyfinishesup.
Eventhoughthisisaverysimpleprogram,Ihavebeenpointingoutalotofthingsthatyoushouldnotice.
Alltheseareprettystraightforward(andsurprisinglysimpleforthoseofyoufromC/C++backgrounds).
Youwillneedtobecomeawareofallthesethingsinitially,butaftersomepracticeyouwillbecome
comfortablewiththem,anditwillallfeel'natural'toyou.
NoteforC/C++Programmers
NOTE

Thereisno switch statementinPython.Youcanusean if..elif..else


statementtodothesamething(andinsomecases,useadictionarytodoitquickly)

9.2.ThewhileStatement
The while statementallowsyoutorepeatedlyexecuteablockofstatementsaslongasaconditionis
true.A while statementisanexampleofwhatiscalledaloopingstatement.A while statementcan
haveanoptional else clause.
Example(saveas while.py ):

http://www.swaroopch.com/notes/python/

59/165

1/4/2015

AByteofPython

number=23
running=True

PYTHON

whilerunning:
guess=int(raw_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,buttheadvantageisthattheuserisallowedto
keepguessinguntilheguessescorrectlythereisnoneedtorepeatedlyruntheprogramforeachguess,
aswehavedoneintheprevioussection.Thisaptlydemonstratestheuseofthe while statement.
Wemovethe raw_input and if statementstoinsidethe while loopandsetthevariable running
to True beforethewhileloop.First,wecheckifthevariable running is True andthenproceedto
executethecorrespondingwhileblock.Afterthisblockisexecuted,theconditionisagainchecked
whichinthiscaseisthe running variable.Ifitistrue,weexecutethewhileblockagain,elsewe
continuetoexecutetheoptionalelseblockandthencontinuetothenextstatement.

http://www.swaroopch.com/notes/python/

60/165

1/4/2015

AByteofPython

The else blockisexecutedwhenthe while loopconditionbecomes False thismayevenbethe


firsttimethattheconditionischecked.Ifthereisan else clausefora while loop,itisalways
executedunlessyoubreakoutoftheloopwitha break statement.
The True and False arecalledBooleantypesandyoucanconsiderthemtobeequivalenttothevalue
1 and 0 respectively.

NOTE

NoteforC/C++Programmers
Rememberthatyoucanhavean else clauseforthe while loop.

9.3.Theforloop
The for..in statementisanotherloopingstatementwhichiteratesoverasequenceofobjectsi.e.go
througheachiteminasequence.Wewillseemoreaboutsequencesindetailinlaterchapters.Whatyou
needtoknowrightnowisthatasequenceisjustanorderedcollectionofitems.
Example(saveas for.py ):
foriinrange(1,5):
printi
else:
print'Theforloopisover'

PYTHON

Output:
$pythonfor.py
1
2
3
4
Theforloopisover

HowItWorks
Inthisprogram,weareprintingasequenceofnumbers.Wegeneratethissequenceofnumbersusingthe
builtin range function.
Whatwedohereissupplyittwonumbersand range returnsasequenceofnumbersstartingfromthe
firstnumberanduptothesecondnumber.Forexample, range(1,5) givesthesequence [1,2,3,
4] .Bydefault, range takesastepcountof1.Ifwesupplyathirdnumberto range ,thenthat

http://www.swaroopch.com/notes/python/

61/165

1/4/2015

AByteofPython

becomesthestepcount.Forexample, range(1,5,2) gives [1,3] .Rememberthattherangeextends


uptothesecondnumberi.e.itdoesnotincludethesecondnumber.
Notethat range() generatesasequenceofnumbers,butitwillgenerateonlyonenumberatatime,
whentheforlooprequestsforthenextitem.Ifyouwanttoseethefullsequenceofnumbers
immediately,use list(range()) .Listsareexplainedinthedatastructureschapter.
The for looptheniteratesoverthisrange foriinrange(1,5) isequivalentto foriin[1,2,
3,4] whichislikeassigningeachnumber(orobject)inthesequencetoi,oneatatime,andthen

executingtheblockofstatementsforeachvalueof i .Inthiscase,wejustprintthevalueintheblockof
statements.
Rememberthatthe else partisoptional.Whenincluded,itisalwaysexecutedonceafterthe for loop
isoverunlessabreakstatementisencountered.
Rememberthatthe for..in loopworksforanysequence.Here,wehavealistofnumbersgenerated
bythebuiltin range function,butingeneralwecanuseanykindofsequenceofanykindofobjects!
Wewillexplorethisideaindetailinlaterchapters.
NoteforC/C++/Java/C#Programmers
ThePython for loopisradicallydifferentfromtheC/C++ for loop.C#
programmerswillnotethatthe for loopinPythonissimilartothe foreach loopin
C#.Javaprogrammerswillnotethatthesameissimilarto for(inti:
NOTE

IntArray) inJava1.5.

InC/C,ifyouwanttowrite`for(inti=0i<5i) ,theninPythonyouwrite
just`foriinrange(0,5) .Asyoucansee,the for loopissimpler,more

expressiveandlesserrorproneinPython.

9.4.ThebreakStatement
The break statementisusedtobreakoutofaloopstatementi.e.stoptheexecutionofalooping
statement,eveniftheloopconditionhasnotbecome False orthesequenceofitemshasnotbeen
completelyiteratedover.
Animportantnoteisthatifyoubreakoutofa for or while loop,anycorrespondingloop else
blockisnotexecuted.
Example(saveas break.py ):

http://www.swaroopch.com/notes/python/

62/165

1/4/2015

AByteofPython

whileTrue:
s=raw_input('Entersomething:')
ifs=='quit':
break
print'Lengthofthestringis',len(s)
print'Done'

PYTHON

Output:
$pythonbreak.py
Entersomething:Programmingisfun
Lengthofthestringis18
Entersomething:Whentheworkisdone
Lengthofthestringis21
Entersomething:ifyouwannamakeyourworkalsofun:
Lengthofthestringis37
Entersomething:usePython!
Lengthofthestringis11
Entersomething:quit
Done

HowItWorks
Inthisprogram,werepeatedlytaketheusersinputandprintthelengthofeachinputeachtime.Weare
providingaspecialconditiontostoptheprogrambycheckingiftheuserinputis 'quit' .Westopthe
programbybreakingoutoftheloopandreachtheendoftheprogram.
Thelengthoftheinputstringcanbefoundoutusingthebuiltin len function.
Rememberthatthe break statementcanbeusedwiththe for loopaswell.

SwaroopsPoeticPython
TheinputIhaveusedhereisaminipoemIhavewritten:

Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!

9.5.ThecontinueStatement
http://www.swaroopch.com/notes/python/

63/165

1/4/2015

AByteofPython

The continue statementisusedtotellPythontoskiptherestofthestatementsinthecurrentloop


blockandtocontinuetothenextiterationoftheloop.
Example(saveas continue.py ):
whileTrue:
s=raw_input('Entersomething:')
ifs=='quit':
break
iflen(s)<3:
print'Toosmall'
continue
print'Inputisofsufficientlength'
#Dootherkindsofprocessinghere...

PYTHON

Output:
$pythoncontinue.py
Entersomething:a
Toosmall
Entersomething:12
Toosmall
Entersomething:abc
Inputisofsufficientlength
Entersomething:quit

HowItWorks
Inthisprogram,weacceptinputfromtheuser,butweprocesstheinputstringonlyifitisatleast3
characterslong.So,weusethebuiltin len functiontogetthelengthandifthelengthislessthan3,we
skiptherestofthestatementsintheblockbyusingthe continue statement.Otherwise,therestofthe
statementsintheloopareexecuted,doinganykindofprocessingwewanttodohere.
Notethatthe continue statementworkswiththe for loopaswell.

9.6.Summary
Wehaveseenhowtousethethreecontrolflowstatements if , while and for alongwiththeir
associated break and continue statements.Thesearesomeofthemostcommonlyusedpartsof
Pythonandhence,becomingcomfortablewiththemisessential.
Next,wewillseehowtocreateandusefunctions.

http://www.swaroopch.com/notes/python/

64/165

1/4/2015

AByteofPython

10.Functions
Functionsarereusablepiecesofprograms.Theyallowyoutogiveanametoablockofstatements,
allowingyoutorunthatblockusingthespecifiednameanywhereinyourprogramandanynumberof
times.Thisisknownascallingthefunction.Wehavealreadyusedmanybuiltinfunctionssuchas len
and range .
Thefunctionconceptisprobablythemostimportantbuildingblockofanynontrivialsoftware(inany
programminglanguage),sowewillexplorevariousaspectsoffunctionsinthischapter.
Functionsaredefinedusingthe def keyword.Afterthiskeywordcomesanidentifiernameforthe
function,followedbyapairofparentheseswhichmayenclosesomenamesofvariables,andbythefinal
colonthatendstheline.Nextfollowstheblockofstatementsthatarepartofthisfunction.Anexample
willshowthatthisisactuallyverysimple:
Example(saveas function1.py ):
defsay_hello():
#blockbelongingtothefunction
print'helloworld'
#Endoffunction

PYTHON

say_hello()#callthefunction
say_hello()#callthefunctionagain

Output:
$pythonfunction1.py
helloworld
helloworld

HowItWorks
Wedefineafunctioncalled say_hello usingthesyntaxasexplainedabove.Thisfunctiontakesno
parametersandhencetherearenovariablesdeclaredintheparentheses.Parameterstofunctionsarejust
inputtothefunctionsothatwecanpassindifferentvaluestoitandgetbackcorrespondingresults.
Noticethatwecancallthesamefunctiontwicewhichmeanswedonothavetowritethesamecode
again.

10.1.FunctionParameters
http://www.swaroopch.com/notes/python/

65/165

1/4/2015

AByteofPython

Afunctioncantakeparameters,whicharevaluesyousupplytothefunctionsothatthefunctioncando
somethingutilisingthosevalues.Theseparametersarejustlikevariablesexceptthatthevaluesofthese
variablesaredefinedwhenwecallthefunctionandarealreadyassignedvalueswhenthefunctionruns.
Parametersarespecifiedwithinthepairofparenthesesinthefunctiondefinition,separatedbycommas.
Whenwecallthefunction,wesupplythevaluesinthesameway.Notetheterminologyusedthenames
giveninthefunctiondefinitionarecalledparameterswhereasthevaluesyousupplyinthefunctioncall
arecalledarguments.
Example(saveas function_param.py ):
defprint_max(a,b):
ifa>b:
printa,'ismaximum'
elifa==b:
printa,'isequalto',b
else:
printb,'ismaximum'

PYTHON

#directlypassliteralvalues
print_max(3,4)
x=5
y=7
#passvariablesasarguments
print_max(x,y)

Output:
$pythonfunction_param.py
4ismaximum
7ismaximum

HowItWorks
Here,wedefineafunctioncalled print_max thatusestwoparameterscalled a and b .Wefindoutthe
greaternumberusingasimple if..else statementandthenprintthebiggernumber.
Thefirsttimewecallthefunction print_max ,wedirectlysupplythenumbersasarguments.Inthe
secondcase,wecallthefunctionwithvariablesasarguments. print_max(x,y) causesthevalueof
argument x tobeassignedtoparameter a andthevalueofargument y tobeassignedtoparameter b .
TheprintMaxfunctionworksthesamewayinbothcases.

http://www.swaroopch.com/notes/python/

66/165

1/4/2015

AByteofPython

10.2.LocalVariables
Whenyoudeclarevariablesinsideafunctiondefinition,theyarenotrelatedinanywaytoothervariables
withthesamenamesusedoutsidethefunctioni.e.variablenamesarelocaltothefunction.Thisis
calledthescopeofthevariable.Allvariableshavethescopeoftheblocktheyaredeclaredinstarting
fromthepointofdefinitionofthename.
Example(saveas function_local.py ):
x=50

PYTHON

deffunc(x):
print'xis',x
x=2
print'Changedlocalxto',x
func(x)
print'xisstill',x

Output:
$pythonfunction_local.py
xis50
Changedlocalxto2
xisstill50

HowItWorks
Thefirsttimethatweprintthevalueofthenamexwiththefirstlineinthefunctionsbody,Pythonuses
thevalueoftheparameterdeclaredinthemainblock,abovethefunctiondefinition.
Next,weassignthevalue 2 to x .Thename x islocaltoourfunction.So,whenwechangethevalue
of x inthefunction,the x definedinthemainblockremainsunaffected.
Withthelast print statement,wedisplaythevalueof x asdefinedinthemainblock,thereby
confirmingthatitisactuallyunaffectedbythelocalassignmentwithinthepreviouslycalledfunction.

10.3.Theglobalstatement
Ifyouwanttoassignavaluetoanamedefinedatthetopleveloftheprogram(i.e.notinsideanykindof
scopesuchasfunctionsorclasses),thenyouhavetotellPythonthatthenameisnotlocal,butitis
global.Wedothisusingthe global statement.Itisimpossibletoassignavaluetoavariabledefined
outsideafunctionwithoutthe global statement.
http://www.swaroopch.com/notes/python/

67/165

1/4/2015

AByteofPython

Youcanusethevaluesofsuchvariablesdefinedoutsidethefunction(assumingthereisnovariablewith
thesamenamewithinthefunction).However,thisisnotencouragedandshouldbeavoidedsinceit
becomesuncleartothereaderoftheprogramastowherethatvariablesdefinitionis.Usingthe global
statementmakesitamplyclearthatthevariableisdefinedinanoutermostblock.
Example(saveas function_global.py ):
x=50

PYTHON

deffunc():
globalx
print'xis',x
x=2
print'Changedglobalxto',x
func()
print'Valueofxis',x

Output:
$pythonfunction_global.py
xis50
Changedglobalxto2
Valueofxis2

HowItWorks
The global statementisusedtodeclarethat x isaglobalvariablehence,whenweassignavalueto
x insidethefunction,thatchangeisreflectedwhenweusethevalueof x inthemainblock.

Youcanspecifymorethanoneglobalvariableusingthesame global statemente.g. globalx,y,


z.

10.4.DefaultArgumentValues
Forsomefunctions,youmaywanttomakesomeparametersoptionalandusedefaultvaluesincasethe
userdoesnotwanttoprovidevaluesforthem.Thisisdonewiththehelpofdefaultargumentvalues.You
canspecifydefaultargumentvaluesforparametersbyappendingtotheparameternameinthefunction
definitiontheassignmentoperator( = )followedbythedefaultvalue.
Notethatthedefaultargumentvalueshouldbeaconstant.Moreprecisely,thedefaultargumentvalue
shouldbeimmutablethisisexplainedindetailinlaterchapters.Fornow,justrememberthis.
http://www.swaroopch.com/notes/python/

68/165

1/4/2015

AByteofPython

Example(saveas function_default.py ):
defsay(message,times=1):
printmessage*times

PYTHON

say('Hello')
say('World',5)

Output:
$pythonfunction_default.py
Hello
WorldWorldWorldWorldWorld

HowItWorks
Thefunctionnamed say isusedtoprintastringasmanytimesasspecified.Ifwedontsupplyavalue,
thenbydefault,thestringisprintedjustonce.Weachievethisbyspecifyingadefaultargumentvalueof
1 totheparameter times .

Inthefirstusageof say ,wesupplyonlythestringanditprintsthestringonce.Inthesecondusageof


say ,wesupplyboththestringandanargument 5 statingthatwewanttosaythestringmessage5

times.
Onlythoseparameterswhichareattheendoftheparameterlistcanbegivendefault
argumentvaluesi.e.youcannothaveaparameterwithadefaultargumentvalue
precedingaparameterwithoutadefaultargumentvalueinthefunctionsparameter
CAUTION

list.
Thisisbecausethevaluesareassignedtotheparametersbyposition.For
example, deffunc(a,b=5) isvalid,but deffunc(a=5,b) isnotvalid.

10.5.KeywordArguments
Ifyouhavesomefunctionswithmanyparametersandyouwanttospecifyonlysomeofthem,thenyou
cangivevaluesforsuchparametersbynamingthemthisiscalledkeywordargumentsweusethe
name(keyword)insteadoftheposition(whichwehavebeenusingallalong)tospecifytheargumentsto
thefunction.

http://www.swaroopch.com/notes/python/

69/165

1/4/2015

AByteofPython

Therearetwoadvantagesone,usingthefunctioniseasiersincewedonotneedtoworryabouttheorder
ofthearguments.Two,wecangivevaluestoonlythoseparameterstowhichwewantto,providedthat
theotherparametershavedefaultargumentvalues.
Example(saveas function_keyword.py ):
deffunc(a,b=5,c=10):
print'ais',a,'andbis',b,'andcis',c

PYTHON

func(3,7)
func(25,c=24)
func(c=50,a=100)

Output:
$pythonfunction_keyword.py
ais3andbis7andcis10
ais25andbis5andcis24
ais100andbis5andcis50

HowItWorks
Thefunctionnamed func hasoneparameterwithoutadefaultargumentvalue,followedbytwo
parameterswithdefaultargumentvalues.
Inthefirstusage, func(3,7) ,theparameter a getsthevalue 3 ,theparameter b getsthevalue 7
and c getsthedefaultvalueof 10 .
Inthesecondusage func(25,c=24) ,thevariable a getsthevalueof25duetothepositionofthe
argument.Then,theparameter c getsthevalueof 24 duetonamingi.e.keywordarguments.The
variable b getsthedefaultvalueof 5 .
Inthethirdusage func(c=50,a=100) ,weusekeywordargumentsforallspecifiedvalues.Noticethat
wearespecifyingthevalueforparameter c beforethatfor a eventhough a isdefinedbefore c inthe
functiondefinition.

10.6.VarArgsparameters
Sometimesyoumightwanttodefineafunctionthatcantakeanynumberofparameters,i.e.variable
numberofarguments,thiscanbeachievedbyusingthestars(saveas function_varargs.py ):

http://www.swaroopch.com/notes/python/

70/165

1/4/2015

AByteofPython

deftotal(initial=5,*numbers,**keywords):
count=initial
fornumberinnumbers:
count+=number
forkeyinkeywords:
count+=keywords[key]
returncount

PYTHON

printtotal(10,1,2,3,vegetables=50,fruits=100)

Output:
$pythonfunction_varargs.py
166

HowItWorks
Whenwedeclareastarredparametersuchas *param ,thenallthepositionalargumentsfromthatpoint
tilltheendarecollectedasatuplecalled'param'.
Similarly,whenwedeclareadoublestarredparametersuchas **param ,thenallthekeyword
argumentsfromthatpointtilltheendarecollectedasadictionarycalled'param'.
Wewillexploretuplesanddictionariesinalaterchapter.

10.7.Thereturnstatement
The return statementisusedtoreturnfromafunctioni.e.breakoutofthefunction.Wecan
optionallyreturnavaluefromthefunctionaswell.
Example(saveas function_return.py ):
defmaximum(x,y):
ifx>y:
returnx
elifx==y:
return'Thenumbersareequal'
else:
returny

PYTHON

printmaximum(2,3)

Output:

http://www.swaroopch.com/notes/python/

71/165

1/4/2015

AByteofPython

$pythonfunction_return.py
3

HowItWorks
The maximum functionreturnsthemaximumoftheparameters,inthiscasethenumberssuppliedtothe
function.Itusesasimple if..else statementtofindthegreatervalueandthenreturnsthatvalue.
Notethata return statementwithoutavalueisequivalentto returnNone . None isaspecialtypein
Pythonthatrepresentsnothingness.Forexample,itisusedtoindicatethatavariablehasnovalueifithas
avalueof None .
Everyfunctionimplicitlycontainsa returnNone statementattheendunlessyouhavewrittenyour
own return statement.Youcanseethisbyrunning printsome_function() wherethefunction
some_function doesnotusethe return statementsuchas:
defsome_function():
pass

PYTHON

The pass statementisusedinPythontoindicateanemptyblockofstatements.

TIP

Thereisabuiltinfunctioncalled max thatalreadyimplementsthe'findmaximum'


functionality,sousethisbuiltinfunctionwheneverpossible.

10.8.DocStrings
Pythonhasaniftyfeaturecalleddocumentationstrings,usuallyreferredtobyitsshortername
docstrings.DocStringsareanimportanttoolthatyoushouldmakeuseofsinceithelpstodocumentthe
programbetterandmakesiteasiertounderstand.Amazingly,wecanevengetthedocstringbackfrom,
sayafunction,whentheprogramisactuallyrunning!
Example(saveas function_docstring.py ):

http://www.swaroopch.com/notes/python/

72/165

1/4/2015

AByteofPython

defprint_max(x,y):
'''Printsthemaximumoftwonumbers.

PYTHON

Thetwovaluesmustbeintegers.'''
#converttointegers,ifpossible
x=int(x)
y=int(y)
ifx>y:
printx,'ismaximum'
else:
printy,'ismaximum'
print_max(3,5)
printprint_max.__doc__

Output:
$pythonfunction_docstring.py
5ismaximum
Printsthemaximumoftwonumbers.
Thetwovaluesmustbeintegers.

HowItWorks
Astringonthefirstlogicallineofafunctionisthedocstringforthatfunction.NotethatDocStringsalso
applytomodulesandclasseswhichwewilllearnaboutintherespectivechapters.
Theconventionfollowedforadocstringisamultilinestringwherethefirstlinestartswithacapital
letterandendswithadot.Thenthesecondlineisblankfollowedbyanydetailedexplanationstarting
fromthethirdline.Youarestronglyadvisedtofollowthisconventionforallyourdocstringsforallyour
nontrivialfunctions.
Wecanaccessthedocstringofthe print_max functionusingthe doc (noticethedouble
underscores)attribute(namebelongingto)ofthefunction.JustrememberthatPythontreatseverything
asanobjectandthisincludesfunctions.Welllearnmoreaboutobjectsinthechapteronclasses.
Ifyouhaveused help() inPython,thenyouhavealreadyseentheusageofdocstrings!Whatitdoesis
justfetchthe doc attributeofthatfunctionanddisplaysitinaneatmannerforyou.Youcantryitouton
thefunctionabovejustinclude help(print_max) inyourprogram.Remembertopressthe q keyto
exit help .

http://www.swaroopch.com/notes/python/

73/165

1/4/2015

AByteofPython

Automatedtoolscanretrievethedocumentationfromyourprograminthismanner.Therefore,Istrongly
recommendthatyouusedocstringsforanynontrivialfunctionthatyouwrite.The pydoc command
thatcomeswithyourPythondistributionworkssimilarlyto help() usingdocstrings.

10.9.Summary
Wehaveseensomanyaspectsoffunctionsbutnotethatwestillhaventcoveredallaspectsofthem.
However,wehavealreadycoveredmostofwhatyoulluseregardingPythonfunctionsonaneveryday
basis.
Next,wewillseehowtouseaswellascreatePythonmodules.

http://www.swaroopch.com/notes/python/

74/165

1/4/2015

AByteofPython

11.Modules
Youhaveseenhowyoucanreusecodeinyourprogrambydefiningfunctionsonce.Whatifyouwanted
toreuseanumberoffunctionsinotherprogramsthatyouwrite?Asyoumighthaveguessed,theanswer
ismodules.
Therearevariousmethodsofwritingmodules,butthesimplestwayistocreateafilewitha .py
extensionthatcontainsfunctionsandvariables.
AnothermethodistowritethemodulesinthenativelanguageinwhichthePythoninterpreteritselfwas
written.Forexample,youcanwritemodulesintheCprogramminglanguage
(http://docs.python.org/2/extending/)andwhencompiled,theycanbeusedfromyourPythoncodewhen

usingthestandardPythoninterpreter.
Amodulecanbeimportedbyanotherprogramtomakeuseofitsfunctionality.Thisishowwecanuse
thePythonstandardlibraryaswell.First,wewillseehowtousethestandardlibrarymodules.
Example(saveas module_using_sys.py ):
importsys

PYTHON

print('Thecommandlineargumentsare:')
foriinsys.argv:
printi
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/sitepackages',
'/usr/local/lib/python2.7/sitepackages']

HowItWorks
http://www.swaroopch.com/notes/python/

75/165

1/4/2015

AByteofPython

First,weimportthe sys moduleusingthe import statement.Basically,thistranslatestoustelling


Pythonthatwewanttousethismodule.The sys modulecontainsfunctionalityrelatedtothePython
interpreteranditsenvironmenti.e.thesystem.
WhenPythonexecutesthe importsys statement,itlooksforthe sys module.Inthiscase,itisoneof
thebuiltinmodules,andhencePythonknowswheretofindit.
Ifitwasnotacompiledmodulei.e.amodulewritteninPython,thenthePythoninterpreterwillsearch
foritinthedirectorieslistedinits sys.path variable.Ifthemoduleisfound,thenthestatementsinthe
bodyofthatmodulearerunandthemoduleismadeavailableforyoutouse.Notethattheinitialization
isdoneonlythefirsttimethatweimportamodule.
The argv variableinthe sys moduleisaccessedusingthedottednotationi.e. sys.argv .Itclearly
indicatesthatthisnameispartofthe sys module.Anotheradvantageofthisapproachisthatthename
doesnotclashwithany argv variableusedinyourprogram.
The sys.argv variableisalistofstrings(listsareexplainedindetailinalaterchapter.Specifically,the
sys.argv containsthelistofcommandlineargumentsi.e.theargumentspassedtoyourprogram

usingthecommandline.
IfyouareusinganIDEtowriteandruntheseprograms,lookforawaytospecifycommandline
argumentstotheprograminthemenus.
Here,whenweexecute pythonmodule_using_sys.pywearearguments ,werunthemodule
module_using_sys.py withthe python commandandtheotherthingsthatfollowarearguments

passedtotheprogram.Pythonstoresthecommandlineargumentsinthe sys.argv variableforusto


use.
Remember,thenameofthescriptrunningisalwaysthefirstargumentinthe sys.argv list.So,inthis
casewewillhave 'module_using_sys.py' as sys.argv[0] , 'we' as sys.argv[1] , 'are' as
sys.argv[2] and 'arguments' as sys.argv[3] .NoticethatPythonstartscountingfrom0and

not1.
The sys.path containsthelistofdirectorynameswheremodulesareimportedfrom.Observethatthe
firststringin sys.path isemptythisemptystringindicatesthatthecurrentdirectoryisalsopartofthe
sys.path whichissameasthe PYTHONPATH environmentvariable.Thismeansthatyoucandirectly

importmoduleslocatedinthecurrentdirectory.Otherwise,youwillhavetoplaceyourmoduleinoneof
thedirectorieslistedin sys.path .

http://www.swaroopch.com/notes/python/

76/165

1/4/2015

AByteofPython

Notethatthecurrentdirectoryisthedirectoryfromwhichtheprogramislaunched.Run importos;
printos.getcwd() tofindoutthecurrentdirectoryofyourprogram.

11.1.Bytecompiled.pycfiles
Importingamoduleisarelativelycostlyaffair,soPythondoessometrickstomakeitfaster.Onewayis
tocreatebytecompiledfileswiththeextension .pyc whichisanintermediateformthatPython
transformstheprograminto(remembertheintroductionsectiononhowPythonworks?).This .pyc file
isusefulwhenyouimportthemodulethenexttimefromadifferentprogramitwillbemuchfaster
sinceaportionoftheprocessingrequiredinimportingamoduleisalreadydone.Also,thesebyte
compiledfilesareplatformindependent.
These .pyc filesareusuallycreatedinthesamedirectoryasthecorresponding .py
NOTE

files.IfPythondoesnothavepermissiontowritetofilesinthatdirectory,thenthe
.pyc fileswillnotbecreated.

11.2.Thefromimportstatement
Ifyouwanttodirectlyimportthe argv variableintoyourprogram(toavoidtypingthe sys. everytime
forit),thenyoucanusethe fromsysimportargv statement.
Ingeneral,youshouldavoidusingthisstatementandusethe import statementinsteadsinceyour
programwillavoidnameclashesandwillbemorereadable.
Example:
frommathimportsqrt
print"Squarerootof16is",sqrt(16)

PYTHON

11.3.Amodules name
Everymodulehasanameandstatementsinamodulecanfindoutthenameoftheirmodule.Thisis
handyfortheparticularpurposeoffiguringoutwhetherthemoduleisbeingrunstandaloneorbeing
imported.Asmentionedpreviously,whenamoduleisimportedforthefirsttime,thecodeitcontainsgets
executed.Wecanusethistomakethemodulebehaveindifferentwaysdependingonwhetheritisbeing
usedbyitselforbeingimportedfromanothermodule.Thiscanbeachievedusingthe name attributeof
themodule.
Example(saveas module_using_name.py ):

http://www.swaroopch.com/notes/python/

77/165

1/4/2015

AByteofPython

if__name__=='__main__':
print'Thisprogramisbeingrunbyitself'
else:
print'Iambeingimportedfromanothermodule'

PYTHON

Output:
$pythonmodule_using_name.py
Thisprogramisbeingrunbyitself
$python
>>>importmodule_using_name
Iambeingimportedfromanothermodule
>>>

HowItWorks
EveryPythonmodulehasits name defined.Ifthisis 'main' ,thatimpliesthatthemoduleisbeingrun
standalonebytheuserandwecantakeappropriateactions.

11.4.MakingYourOwnModules
Creatingyourownmodulesiseasy,youvebeendoingitallalong!ThisisbecauseeveryPython
programisalsoamodule.Youjusthavetomakesureithasa .py extension.Thefollowingexample
shouldmakeitclear.
Example(saveas mymodule.py ):
defsay_hi():
print'Hi,thisismymodulespeaking.'

PYTHON

__version__='0.1'

Theabovewasasamplemodule.Asyoucansee,thereisnothingparticularlyspecialaboutitcompared
toourusualPythonprogram.WewillnextseehowtousethismoduleinourotherPythonprograms.
Rememberthatthemoduleshouldbeplacedeitherinthesamedirectoryastheprogramfromwhichwe
importit,orinoneofthedirectorieslistedin sys.path .
Anothermodule(saveas mymodule_demo.py ):

http://www.swaroopch.com/notes/python/

78/165

1/4/2015

AByteofPython

importmymodule

PYTHON

mymodule.say_hi()
print'Version',mymodule.__version__

Output:
$pythonmymodule_demo.py
Hi,thisismymodulespeaking.
Version0.1

HowItWorks
Noticethatweusethesamedottednotationtoaccessmembersofthemodule.Pythonmakesgoodreuse
ofthesamenotationtogivethedistinctive'Pythonic'feeltoitsothatwedonthavetokeeplearningnew
waystodothings.
Hereisaversionutilisingthe from..import syntax(saveas mymodule_demo2.py ):
frommymoduleimportsay_hi,__version__

PYTHON

say_hi()
print'Version',__version__

Theoutputof mymodule_demo2.py issameastheoutputof mymodule_demo.py .


Noticethatiftherewasalreadya version namedeclaredinthemodulethatimportsmymodule,there
wouldbeaclash.Thisisalsolikelybecauseitiscommonpracticeforeachmoduletodeclareitsversion
numberusingthisname.Hence,itisalwaysrecommendedtopreferthe import statementeventhough
itmightmakeyourprogramalittlelonger.
Youcouldalsouse:
frommymoduleimport*

PYTHON

Thiswillimportallpublicnamessuchas say_hi butwouldnotimport version becauseitstartswith


doubleunderscores.

WARNING

Rememberthatyoushouldavoidusingimportstar,i.e. frommymoduleimport
*.

http://www.swaroopch.com/notes/python/

79/165

1/4/2015

AByteofPython

ZenofPython
OneofPythonsguidingprinciplesisthat"ExplicitisbetterthanImplicit".Run importthis in
PythontolearnmoreandseethisStackOverflowdiscussion
(http://stackoverflow.com/questions/228181/zenofpython)whichlistsexamplesforeachofthe

principles.

11.5.Thedirfunction
Youcanusethebuiltin dir functiontolisttheidentifiersthatanobjectdefines.Forexample,fora
module,theidentifiersincludethefunctions,classesandvariablesdefinedinthatmodule.
Whenyousupplyamodulenametothe`dir()`function,itreturnsthelistofthenamesdefinedinthat
module.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
http://www.swaroopch.com/notes/python/

80/165

1/4/2015

AByteofPython

First,weseetheusageof dir ontheimported sys module.Wecanseethehugelistofattributesthatit


contains.
Next,weusethe dir functionwithoutpassingparameterstoit.Bydefault,itreturnsthelistofattributes
forthecurrentmodule.Noticethatthelistofimportedmodulesisalsopartofthislist.
Inordertoobservethe dir inaction,wedefineanewvariable a andassignitavalueandthencheck
dir andweobservethatthereisanadditionalvalueinthelistofthesamename.Weremovethe

variable/attributeofthecurrentmoduleusingthe del statementandthechangeisreflectedagaininthe


outputofthe dir function.
Anoteon del thisstatementisusedtodeleteavariable/nameandafterthestatementhasrun,inthis
case dela ,youcannolongeraccessthevariable a itisasifitneverexistedbeforeatall.
Notethatthe dir() functionworksonanyobject.Forexample,run dir(print) tolearnaboutthe
attributesoftheprintfunction,or dir(str) fortheattributesofthestrclass.
Thereisalsoa vars() (http://docs.python.org/2/library/functions.html#vars)functionwhichcanpotentially
giveyoutheattributesandtheirvalues,butitwillnotworkforallcases.

11.6.Packages
Bynow,youmusthavestartedobservingthehierarchyoforganizingyourprograms.Variablesusuallygo
insidefunctions.Functionsandglobalvariablesusuallygoinsidemodules.Whatifyouwantedto
organizemodules?Thatswherepackagescomeintothepicture.
Packagesarejustfoldersofmoduleswithaspecial init.py filethatindicatestoPythonthatthisfolder
isspecialbecauseitcontainsPythonmodules.
Letssayyouwanttocreateapackagecalled'world'withsubpackages'asia','africa',etc.andthese
subpackagesinturncontainmoduleslike'india','madagascar',etc.
Thisishowyouwouldstructurethefolders:

http://www.swaroopch.com/notes/python/

81/165

1/4/2015

AByteofPython

<somefolderpresentinthesys.path>/
world/
__init__.py
asia/
__init__.py
india/
__init__.py
foo.py
africa/
__init__.py
madagascar/
__init__.py
bar.py

Packagesarejustaconveniencetohierarchicallyorganizemodules.Youwillseemanyinstancesofthis
inthestandardlibrary.

11.7.Summary
Justlikefunctionsarereusablepartsofprograms,modulesarereusableprograms.Packagesareanother
hierarchytoorganizemodules.ThestandardlibrarythatcomeswithPythonisanexampleofsuchaset
ofpackagesandmodules.
Wehaveseenhowtousethesemodulesandcreateourownmodules.
Next,wewilllearnaboutsomeinterestingconceptscalleddatastructures.

http://www.swaroopch.com/notes/python/

82/165

1/4/2015

AByteofPython

12.DataStructures
Datastructuresarebasicallyjustthattheyarestructureswhichcanholdsomedatatogether.Inother
words,theyareusedtostoreacollectionofrelateddata.
TherearefourbuiltindatastructuresinPythonlist,tuple,dictionaryandset.Wewillseehowtouse
eachofthemandhowtheymakelifeeasierforus.

12.1.List
A list isadatastructurethatholdsanorderedcollectionofitemsi.e.youcanstoreasequenceof
itemsinalist.Thisiseasytoimagineifyoucanthinkofashoppinglistwhereyouhavealistofitemsto
buy,exceptthatyouprobablyhaveeachitemonaseparatelineinyourshoppinglistwhereasinPython
youputcommasinbetweenthem.
ThelistofitemsshouldbeenclosedinsquarebracketssothatPythonunderstandsthatyouarespecifying
alist.Onceyouhavecreatedalist,youcanadd,removeorsearchforitemsinthelist.Sincewecanadd
andremoveitems,wesaythatalistisamutabledatatypei.e.thistypecanbealtered.

12.2.QuickIntroductionToObjectsAndClasses
AlthoughIvebeengenerallydelayingthediscussionofobjectsandclassestillnow,alittleexplanationis
neededrightnowsothatyoucanunderstandlistsbetter.Wewillexplorethistopicindetailinalater
chapter.
Alistisanexampleofusageofobjectsandclasses.Whenweuseavariable i andassignavaluetoit,
sayinteger 5 toit,youcanthinkofitascreatinganobject(i.e.instance) i ofclass(i.e.type) int .In
fact,youcanread help(int) tounderstandthisbetter.
Aclasscanalsohavemethodsi.e.functionsdefinedforusewithrespecttothatclassonly.Youcanuse
thesepiecesoffunctionalityonlywhenyouhaveanobjectofthatclass.Forexample,Pythonprovidesan
append methodforthe list classwhichallowsyoutoaddanitemtotheendofthelist.Forexample,
mylist.append('anitem') willaddthatstringtothelist mylist .Notetheuseofdottednotation

foraccessingmethodsoftheobjects.
Aclasscanalsohavefieldswhicharenothingbutvariablesdefinedforusewithrespecttothatclass
only.Youcanusethesevariables/namesonlywhenyouhaveanobjectofthatclass.Fieldsarealso
accessedbythedottednotation,forexample, mylist.field .
Example(saveas ds_using_list.py ):

http://www.swaroopch.com/notes/python/

83/165

1/4/2015

AByteofPython

#Thisismyshoppinglist
shoplist=['apple','mango','carrot','banana']

PYTHON

print'Ihave',len(shoplist),'itemstopurchase.'
print'Theseitemsare:',
foriteminshoplist:
printitem,
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
Thevariable shoplist isashoppinglistforsomeonewhoisgoingtothemarket.In shoplist ,we
onlystorestringsofthenamesoftheitemstobuybutyoucanaddanykindofobjecttoalistincluding
numbersandevenotherlists.
Wehavealsousedthe for..in looptoiteratethroughtheitemsofthelist.Bynow,youmusthave
realisedthatalistisalsoasequence.Thespecialityofsequenceswillbediscussedinalatersection.

http://www.swaroopch.com/notes/python/

84/165

1/4/2015

AByteofPython

Noticetheuseofthetrailingcommainthe print statementtoindicatethatwewanttoendtheoutput


withaspaceinsteadoftheusuallinebreak.ThinkofthecommaastellingPythonthatwehavemore
itemstoprintonthesameline.
Next,weaddanitemtothelistusingthe append methodofthelistobject,asalreadydiscussedbefore.
Then,wecheckthattheitemhasbeenindeedaddedtothelistbyprintingthecontentsofthelistby
simplypassingthelisttothe print statementwhichprintsitneatly.
Then,wesortthelistbyusingthe sort methodofthelist.Itisimportanttounderstandthatthismethod
affectsthelistitselfanddoesnotreturnamodifiedlistthisisdifferentfromthewaystringswork.This
iswhatwemeanbysayingthatlistsaremutableandthatstringsareimmutable.
Next,whenwefinishbuyinganiteminthemarket,wewanttoremoveitfromthelist.Weachievethis
byusingthe del statement.Here,wementionwhichitemofthelistwewanttoremoveandthe del
statementremovesitfromthelistforus.Wespecifythatwewanttoremovethefirstitemfromthelist
andhenceweuse delshoplist[0] (rememberthatPythonstartscountingfrom0).
Ifyouwanttoknowallthemethodsdefinedbythelistobject,see help(list) fordetails.

12.3.Tuple
Tuplesareusedtoholdtogethermultipleobjects.Thinkofthemassimilartolists,butwithoutthe
extensivefunctionalitythatthelistclassgivesyou.Onemajorfeatureoftuplesisthattheyare
immutablelikestringsi.e.youcannotmodifytuples.
Tuplesaredefinedbyspecifyingitemsseparatedbycommaswithinanoptionalpairofparentheses.
Tuplesareusuallyusedincaseswhereastatementorauserdefinedfunctioncansafelyassumethatthe
collectionofvaluesi.e.thetupleofvaluesusedwillnotchange.
Example(saveas ds_using_tuple.py ):

http://www.swaroopch.com/notes/python/

85/165

1/4/2015

AByteofPython

#Iwouldrecommendalwaysusingparentheses
#toindicatestartandendoftuple
#eventhoughparenthesesareoptional.
#Explicitisbetterthanimplicit.
zoo=('python','elephant','penguin')
print'Numberofanimalsinthezoois',len(zoo)

PYTHON

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
Thevariable zoo referstoatupleofitems.Weseethatthe len functioncanbeusedtogetthelength
ofthetuple.Thisalsoindicatesthatatupleisasequenceaswell.
Wearenowshiftingtheseanimalstoanewzoosincetheoldzooisbeingclosed.Therefore,the
new_zoo tuplecontainssomeanimalswhicharealreadytherealongwiththeanimalsbroughtoverfrom

theoldzoo.Backtoreality,notethatatuplewithinatupledoesnotloseitsidentity.
Wecanaccesstheitemsinthetuplebyspecifyingtheitemspositionwithinapairofsquarebracketsjust
likewedidforlists.Thisiscalledtheindexingoperator.Weaccessthethirditemin new_zoo by
specifying new_zoo[2] andweaccessthethirditemwithinthethirditeminthe new_zoo tupleby
specifying new_zoo[2][2] .Thisisprettysimpleonceyouveunderstoodtheidiom.
Tuplewith0or1items
Anemptytupleisconstructedbyanemptypairofparenthesessuchas myempty=
NOTE

() .However,atuplewithasingleitemisnotsosimple.Youhavetospecifyitusing

acommafollowingthefirst(andonly)itemsothatPythoncandifferentiatebetweena

http://www.swaroopch.com/notes/python/

86/165

1/4/2015

AByteofPython

tupleandapairofparenthesessurroundingtheobjectinanexpressioni.e.youhaveto
specify singleton=(2,) ifyoumeanyouwantatuplecontainingtheitem 2 .

NoteforPerlprogrammers
Alistwithinalistdoesnotloseitsidentityi.e.listsarenotflattenedasinPerl.The
NOTE

sameappliestoatuplewithinatuple,oratuplewithinalist,oralistwithinatuple,
etc.AsfarasPythonisconcerned,theyarejustobjectsstoredusinganotherobject,
thatsall.

12.4.Dictionary
Adictionaryislikeanaddressbookwhereyoucanfindtheaddressorcontactdetailsofapersonby
knowingonlyhis/hernamei.e.weassociatekeys(name)withvalues(details).Notethatthekeymustbe
uniquejustlikeyoucannotfindoutthecorrectinformationifyouhavetwopersonswiththeexactsame
name.
Notethatyoucanuseonlyimmutableobjects(likestrings)forthekeysofadictionarybutyoucanuse
eitherimmutableormutableobjectsforthevaluesofthedictionary.Thisbasicallytranslatestosaythat
youshoulduseonlysimpleobjectsforkeys.
Pairsofkeysandvaluesarespecifiedinadictionarybyusingthenotation d={key1:value1,key2
:value2} .Noticethatthekeyvaluepairsareseparatedbyacolonandthepairsareseparated

themselvesbycommasandallthisisenclosedinapairofcurlybraces.
Rememberthatkeyvaluepairsinadictionaryarenotorderedinanymanner.Ifyouwantaparticular
order,thenyouwillhavetosortthemyourselfbeforeusingit.
Thedictionariesthatyouwillbeusingareinstances/objectsofthe dict class.
Example(saveas ds_using_dict.py ):

http://www.swaroopch.com/notes/python/

87/165

1/4/2015

AByteofPython

#'ab'isshortfor'a'ddress'b'ook

PYTHON

ab={'Swaroop':'swaroop@swaroopch.com',
'Larry':'larry@wall.org',
'Matsumoto':'matz@rubylang.org',
'Spammer':'spammer@hotmail.com'
}
print"Swaroop'saddressis",ab['Swaroop']
#Deletingakeyvaluepair
delab['Spammer']
print'\nThereare{}contactsintheaddressbook\n'.format(len(ab))
forname,addressinab.items():
print'Contact{}at{}'.format(name,address)
#Addingakeyvaluepair
ab['Guido']='guido@python.org'
if'Guido'inab:
print"\nGuido'saddressis",ab['Guido']

Output:
$pythonds_using_dict.py
Swaroop'saddressisswaroop@swaroopch.com
Thereare3contactsintheaddressbook
ContactSwaroopatswaroop@swaroopch.com
ContactMatsumotoatmatz@rubylang.org
ContactLarryatlarry@wall.org
Guido'saddressisguido@python.org

HowItWorks
Wecreatethedictionary ab usingthenotationalreadydiscussed.Wethenaccesskeyvaluepairsby
specifyingthekeyusingtheindexingoperatorasdiscussedinthecontextoflistsandtuples.Observethe
simplesyntax.
Wecandeletekeyvaluepairsusingouroldfriendthe del statement.Wesimplyspecifythedictionary
andtheindexingoperatorforthekeytoberemovedandpassittothe del statement.Thereisnoneedto
knowthevaluecorrespondingtothekeyforthisoperation.

http://www.swaroopch.com/notes/python/

88/165

1/4/2015

AByteofPython

Next,weaccesseachkeyvaluepairofthedictionaryusingthe items methodofthedictionarywhich


returnsalistoftupleswhereeachtuplecontainsapairofitemsthekeyfollowedbythevalue.We
retrievethispairandassignittothevariables name and address correspondinglyforeachpairusing
the for..in loopandthenprintthesevaluesintheforblock.
Wecanaddnewkeyvaluepairsbysimplyusingtheindexingoperatortoaccessakeyandassignthat
value,aswehavedoneforGuidointheabovecase.
Wecancheckifakeyvaluepairexistsusingthe in operator.
Forthelistofmethodsofthe dict class,see help(dict) .
KeywordArgumentsandDictionaries
Ifyouhaveusedkeywordargumentsinyourfunctions,youhavealreadyused
TIP

dictionaries!Justthinkaboutitthekeyvaluepairisspecifiedbyyouinthe
parameterlistofthefunctiondefinitionandwhenyouaccessvariableswithinyour
function,itisjustakeyaccessofadictionary(whichiscalledthesymboltablein
compilerdesignterminology).

12.5.Sequence
Lists,tuplesandstringsareexamplesofsequences,butwhataresequencesandwhatissospecialabout
them?
Themajorfeaturesaremembershiptests,(i.e.the in and notin expressions)andindexing
operations,whichallowustofetchaparticulariteminthesequencedirectly.
Thethreetypesofsequencesmentionedabovelists,tuplesandstrings,alsohaveaslicingoperation
whichallowsustoretrieveasliceofthesequencei.e.apartofthesequence.
Example(saveas ds_seq.py ):

http://www.swaroopch.com/notes/python/

89/165

1/4/2015

AByteofPython

shoplist=['apple','mango','carrot','banana']
name='swaroop'

PYTHON

#Indexingor'Subscription'operation#
print'Item0is',shoplist[0]
print'Item1is',shoplist[1]
print'Item2is',shoplist[2]
print'Item3is',shoplist[3]
print'Item1is',shoplist[1]
print'Item2is',shoplist[2]
print'Character0is',name[0]
#Slicingonalist#
print'Item1to3is',shoplist[1:3]
print'Item2toendis',shoplist[2:]
print'Item1to1is',shoplist[1:1]
print'Itemstarttoendis',shoplist[:]
#Slicingonastring#
print'characters1to3is',name[1:3]
print'characters2toendis',name[2:]
print'characters1to1is',name[1:1]
print'charactersstarttoendis',name[:]

Output:
$pythonds_seq.py
Item0isapple
Item1ismango
Item2iscarrot
Item3isbanana
Item1isbanana
Item2iscarrot
Character0iss
Item1to3is['mango','carrot']
Item2toendis['carrot','banana']
Item1to1is['mango','carrot']
Itemstarttoendis['apple','mango','carrot','banana']
characters1to3iswa
characters2toendisaroop
characters1to1iswaroo
charactersstarttoendisswaroop

HowItWorks
First,weseehowtouseindexestogetindividualitemsofasequence.Thisisalsoreferredtoasthe
subscriptionoperation.Wheneveryouspecifyanumbertoasequencewithinsquarebracketsasshown
above,Pythonwillfetchyoutheitemcorrespondingtothatpositioninthesequence.Rememberthat
http://www.swaroopch.com/notes/python/

90/165

1/4/2015

AByteofPython

Pythonstartscountingnumbersfrom0.Hence, shoplist[0] fetchesthefirstitemand shoplist[3]


fetchesthefourthiteminthe`shoplist`sequence.
Theindexcanalsobeanegativenumber,inwhichcase,thepositioniscalculatedfromtheendofthe
sequence.Therefore, shoplist[1] referstothelastiteminthesequenceand shoplist[2] fetches
thesecondlastiteminthesequence.
Theslicingoperationisusedbyspecifyingthenameofthesequencefollowedbyanoptionalpairof
numbersseparatedbyacolonwithinsquarebrackets.Notethatthisisverysimilartotheindexing
operationyouhavebeenusingtillnow.Rememberthenumbersareoptionalbutthecolonisnt.
Thefirstnumber(beforethecolon)intheslicingoperationreferstothepositionfromwheretheslice
startsandthesecondnumber(afterthecolon)indicateswheretheslicewillstopat.Ifthefirstnumberis
notspecified,Pythonwillstartatthebeginningofthesequence.Ifthesecondnumberisleftout,Python
willstopattheendofthesequence.Notethattheslicereturnedstartsatthestartpositionandwillend
justbeforetheendpositioni.e.thestartpositionisincludedbuttheendpositionisexcludedfromthe
sequenceslice.
Thus, shoplist[1:3] returnsasliceofthesequencestartingatposition1,includesposition2but
stopsatposition3andthereforeasliceoftwoitemsisreturned.Similarly, shoplist[:] returnsacopy
ofthewholesequence.
Youcanalsodoslicingwithnegativepositions.Negativenumbersareusedforpositionsfromtheendof
thesequence.Forexample, shoplist[:1] willreturnasliceofthesequencewhichexcludesthelast
itemofthesequencebutcontainseverythingelse.
Youcanalsoprovideathirdargumentfortheslice,whichisthestepfortheslicing(bydefault,thestep
sizeis1):
>>>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']

PYTHON

Noticethatwhenthestepis2,wegettheitemswithposition0,2,Whenthestepsizeis3,wegetthe
itemswithposition0,3,etc.
http://www.swaroopch.com/notes/python/

91/165

1/4/2015

AByteofPython

TryvariouscombinationsofsuchslicespecificationsusingthePythoninterpreterinteractivelyi.e.the
promptsothatyoucanseetheresultsimmediately.Thegreatthingaboutsequencesisthatyoucan
accesstuples,listsandstringsallinthesameway!

12.6.Set
Setsareunorderedcollectionsofsimpleobjects.Theseareusedwhentheexistenceofanobjectina
collectionismoreimportantthantheorderorhowmanytimesitoccurs.
Usingsets,youcantestformembership,whetheritisasubsetofanotherset,findtheintersection
betweentwosets,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'}

PYTHON

HowItWorks
Theexampleisprettymuchselfexplanatorybecauseitinvolvesbasicsettheorymathematicstaughtin
school.

12.7.References
Whenyoucreateanobjectandassignittoavariable,thevariableonlyreferstotheobjectanddoesnot
representtheobjectitself!Thatis,thevariablenamepointstothatpartofyourcomputersmemory
wheretheobjectisstored.Thisiscalledbindingthenametotheobject.
Generally,youdontneedtobeworriedaboutthis,butthereisasubtleeffectduetoreferenceswhich
youneedtobeawareof:
Example(saveas ds_reference.py ):

http://www.swaroopch.com/notes/python/

92/165

1/4/2015

AByteofPython

print'SimpleAssignment'
shoplist=['apple','mango','carrot','banana']
#mylistisjustanothernamepointingtothesameobject!
mylist=shoplist

PYTHON

#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(not
simpleobjectssuchasintegers),thenyouhavetousetheslicingoperationtomakeacopy.Ifyoujust
assignthevariablenametoanothername,bothofthemwill''refer''tothesameobjectandthiscouldbe
troubleifyouarenotcareful.
NoteforPerlprogrammers
NOTE

Rememberthatanassignmentstatementforlistsdoesnotcreateacopy.Youhaveto
useslicingoperationtomakeacopyofthesequence.

http://www.swaroopch.com/notes/python/

93/165

1/4/2015

AByteofPython

12.8.MoreAboutStrings
Wehavealreadydiscussedstringsindetailearlier.Whatmorecantherebetoknow?Well,didyouknow
thatstringsarealsoobjectsandhavemethodswhichdoeverythingfromcheckingpartofastringto
strippingspaces!
Thestringsthatyouuseinprogramareallobjectsoftheclass str .Someusefulmethodsofthisclass
aredemonstratedinthenextexample.Foracompletelistofsuchmethods,see help(str) .
Example(saveas ds_str_methods.py ):
#Thisisastringobject
name='Swaroop'

PYTHON

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']
printdelimiter.join(mylist)

Output:
$pythonds_str_methods.py
Yes,thestringstartswith"Swa"
Yes,itcontainsthestring"a"
Yes,itcontainsthestring"war"
Brazil_*_Russia_*_India_*_China

HowItWorks
Here,weseealotofthestringmethodsinaction.The startswith methodisusedtofindoutwhether
thestringstartswiththegivenstring.The in operatorisusedtocheckifagivenstringisapartofthe
string.

http://www.swaroopch.com/notes/python/

94/165

1/4/2015

AByteofPython

The find methodisusedtolocatethepositionofthegivensubstringwithinthestring find returns1


ifitisunsuccessfulinfindingthesubstring.The str classalsohasaneatmethodto join theitemsof
asequencewiththestringactingasadelimiterbetweeneachitemofthesequenceandreturnsabigger
stringgeneratedfromthis.

12.9.Summary
WehaveexploredthevariousbuiltindatastructuresofPythonindetail.Thesedatastructureswillbe
essentialforwritingprogramsofreasonablesize.
NowthatwehavealotofthebasicsofPythoninplace,wewillnextseehowtodesignandwriteareal
worldPythonprogram.

http://www.swaroopch.com/notes/python/

95/165

1/4/2015

AByteofPython

13.ProblemSolving
WehaveexploredvariouspartsofthePythonlanguageandnowwewilltakealookathowalltheseparts
fittogether,bydesigningandwritingaprogramwhichdoessomethinguseful.Theideaistolearnhowto
writeaPythonscriptonyourown.

13.1.TheProblem
Theproblemwewanttosolveis:

Iwantaprogramwhichcreatesabackupofallmyimportantfiles.

Although,thisisasimpleproblem,thereisnotenoughinformationforustogetstartedwiththesolution.
Alittlemoreanalysisisrequired.Forexample,howdowespecifywhichfilesaretobebackedup?How
aretheystored?Wherearetheystored?
Afteranalyzingtheproblemproperly,wedesignourprogram.Wemakealistofthingsabouthowour
programshouldwork.Inthiscase,IhavecreatedthefollowinglistonhowIwantittowork.Ifyoudo
thedesign,youmaynotcomeupwiththesamekindofanalysissinceeverypersonhastheirownwayof
doingthings,sothatisperfectlyokay.
Thefilesanddirectoriestobebackeduparespecifiedinalist.
Thebackupmustbestoredinamainbackupdirectory.
Thefilesarebackedupintoazipfile.
Thenameoftheziparchiveisthecurrentdateandtime.
Weusethestandard zip commandavailablebydefaultinanystandardGNU/LinuxorUnix
distribution.Notethatyoucanuseanyarchivingcommandyouwantaslongasithasacommand
lineinterface.
ForWindowsusers
Windowsuserscaninstall (http://gnuwin32.sourceforge.net/downlinks/zip.php)the zip
NOTE

commandfromtheGnuWin32projectpage
(http://gnuwin32.sourceforge.net/packages/zip.htm)andadd C:\Program

Files\GnuWin32\bin toyoursystem PATH environmentvariable,similartowhat

wedidforrecognizingthepythoncommanditself.

13.2.TheSolution
http://www.swaroopch.com/notes/python/

96/165

1/4/2015

AByteofPython

Asthedesignofourprogramisnowreasonablystable,wecanwritethecodewhichisan
implementationofoursolution.
Saveas backup_ver1.py :
importos
importtime

PYTHON

#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="zipr{0}{1}".format(target,
''.join(source))
#Runthebackup
print"Zipcommandis:"
printzip_command
print"Running:"
ifos.system(zip_command)==0:
print'Successfulbackupto',target
else:
print'BackupFAILED'

Output:

http://www.swaroopch.com/notes/python/

97/165

1/4/2015

AByteofPython

$pythonbackup_ver1.py
Zipcommandis:
zipr/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.Ifitdoesntbehaveas
expected,thenwehavetodebugourprogrami.e.removethebugs(errors)fromtheprogram.
Iftheaboveprogramdoesnotworkforyou,copythelineprintedafterthe Zipcommandis lineinthe
output,pasteitintheshell(onGNU/LinuxandMacOSX)/ cmd (onWindows),seewhattheerroris
andtrytofixit.Alsocheckthezipcommandmanualonwhatcouldbewrong.Ifthiscommandsucceeds,
thentheproblemmightbeinthePythonprogramitself,socheckifitexactlymatchestheprogram
writtenabove.
HowItWorks
Youwillnoticehowwehaveconvertedourdesignintocodeinastepbystepmanner.
Wemakeuseofthe os and time modulesbyfirstimportingthem.Then,wespecifythefilesand
directoriestobebackedupinthe source list.Thetargetdirectoryiswherewestoreallthebackupfiles
andthisisspecifiedinthe target_dir variable.Thenameoftheziparchivethatwearegoingtocreate
isthecurrentdateandtimewhichwegenerateusingthe time.strftime() function.Itwillalsohave
the .zip extensionandwillbestoredinthe target_dir directory.
Noticetheuseofthe os.sep variablethisgivesthedirectoryseparatoraccordingtoyouroperating
systemi.e.itwillbe '/' inGNU/LinuxandUnix,itwillbe '\\' inWindowsand ':' inMacOS.
Using os.sep insteadofthesecharactersdirectlywillmakeourprogramportableandworkacrossall
ofthesesystems.
The time.strftime() functiontakesaspecificationsuchastheonewehaveusedintheabove
program.The %Y specificationwillbereplacedbytheyearwiththecentury.The %m specificationwill
bereplacedbythemonthasadecimalnumberbetween 01 and 12 andsoon.Thecompletelistofsuch
specificationscanbefoundinthePythonReferenceManual
(http://docs.python.org/2/library/time.html#time.strftime).

http://www.swaroopch.com/notes/python/

98/165

1/4/2015

AByteofPython

Wecreatethenameofthetargetzipfileusingtheadditionoperatorwhichconcatenatesthestringsi.e.it
joinsthetwostringstogetherandreturnsanewone.Then,wecreateastring zip_command which
containsthecommandthatwearegoingtoexecute.Youcancheckifthiscommandworksbyrunningit
intheshell(GNU/LinuxterminalorDOSprompt).
The zip commandthatweareusinghassomeoptionsandparameterspassed.The r optionspecifies
thatthezipcommandshouldworkrecursivelyfordirectoriesi.e.itshouldincludeallthesubdirectories
andfiles.Thetwooptionsarecombinedandspecifiedinashortcutas qr .Theoptionsarefollowedby
thenameoftheziparchivetocreatefollowedbythelistoffilesanddirectoriestobackup.Weconvert
the source listintoastringusingthe join methodofstringswhichwehavealreadyseenhowtouse.
Then,wefinallyrunthecommandusingthe os.system functionwhichrunsthecommandasifitwas
runfromthesystemi.e.intheshellitreturns 0 ifthecommandwassuccessfully,elseitreturnsan
errornumber.
Dependingontheoutcomeofthecommand,weprinttheappropriatemessagethatthebackuphasfailed
orsucceeded.
Thatsit,wehavecreatedascripttotakeabackupofourimportantfiles!
NotetoWindowsUsers
NOTE

Insteadofdoublebackslashescapesequences,youcanalsouserawstrings.For
example,use 'C:\\Documents' or rC:\Documents' .However,donotuse
'C:\Documents' sinceyouendupusinganunknownescapesequence \D .

Nowthatwehaveaworkingbackupscript,wecanuseitwheneverwewanttotakeabackupofthefiles.
Thisiscalledtheoperationphaseorthedeploymentphaseofthesoftware.
Theaboveprogramworksproperly,but(usually)firstprogramsdonotworkexactlyasyouexpect.For
example,theremightbeproblemsifyouhavenotdesignedtheprogramproperlyorifyouhavemadea
mistakewhentypingthecode,etc.Appropriately,youwillhavetogobacktothedesignphaseoryou
willhavetodebugyourprogram.

13.3.SecondVersion
Thefirstversionofourscriptworks.However,wecanmakesomerefinementstoitsothatitcanwork
betteronadailybasis.Thisiscalledthemaintenancephaseofthesoftware.

http://www.swaroopch.com/notes/python/

99/165

1/4/2015

AByteofPython

OneoftherefinementsIfeltwasusefulisabetterfilenamingmechanismusingthetimeasthenameof
thefilewithinadirectorywiththecurrentdateasadirectorywithinthemainbackupdirectory.Thefirst
advantageisthatyourbackupsarestoredinahierarchicalmannerandthereforeitismucheasierto
manage.Thesecondadvantageisthatthefilenamesaremuchshorter.Thethirdadvantageisthatseparate
directorieswillhelpyoucheckifyouhavemadeabackupforeachdaysincethedirectorywouldbe
createdonlyifyouhavemadeabackupforthatday.
Saveas backup_ver2.py :

http://www.swaroopch.com/notes/python/

100/165

1/4/2015

AByteofPython

importos
importtime

PYTHON

#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="zipr{0}{1}".format(target,
''.join(source))
#Runthebackup
print"Zipcommandis:"
printzip_command
print"Running:"
ifos.system(zip_command)==0:
print'Successfulbackupto',target
else:
print'BackupFAILED'

http://www.swaroopch.com/notes/python/

101/165

1/4/2015

AByteofPython

Output:
$pythonbackup_ver2.py
Successfullycreateddirectory/Users/swa/backup/20140329
Zipcommandis:
zipr/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.Thechangesarethatwecheckifthereisadirectorywiththe
currentdayasitsnameinsidethemainbackupdirectoryusingthe os.path.exists function.Ifit
doesntexist,wecreateitusingthe os.mkdir function.

13.4.ThirdVersion
ThesecondversionworksfinewhenIdomanybackups,butwhentherearelotsofbackups,Iamfinding
ithardtodifferentiatewhatthebackupswerefor!Forexample,Imighthavemadesomemajorchanges
toaprogramorpresentation,thenIwanttoassociatewhatthosechangesarewiththenameofthezip
archive.Thiscanbeeasilyachievedbyattachingausersuppliedcommenttothenameoftheziparchive.

WARNING

Thefollowingprogramdoesnotwork,sodonotbealarmed,pleasefollowalong
becausetheresalessoninhere.

Saveas backup_ver3.py :
importos
importtime

PYTHON

#1.Thefilesanddirectoriestobebackedupare
#specifiedinalist.
#ExampleonWindows:
#source=['"C:\\MyDocuments"','C:\\Code']
#ExampleonMacOSXandLinux:
source=['/Users/swa/notes']
#Noticewehadtousedoublequotesinsidethestring
#fornameswithspacesinit.
#2.Thebackupmustbestoredina
#mainbackupdirectory
http://www.swaroopch.com/notes/python/

102/165

1/4/2015

AByteofPython

#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=raw_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="zipr{0}{1}".format(target,
''.join(source))
#Runthebackup
print"Zipcommandis:"
printzip_command
print"Running:"
ifos.system(zip_command)==0:
print'Successfulbackupto',target
else:
print'BackupFAILED'

Output:

http://www.swaroopch.com/notes/python/

103/165

1/4/2015

AByteofPython

$pythonbackup_ver3.py
File"backup_ver3.py",line39
target=today+os.sep+now+'_'+
^
SyntaxError:invalidsyntax

HowThis(doesnot)Work
Thisprogramdoesnotwork!Pythonsaysthereisasyntaxerrorwhichmeansthatthescriptdoesnot
satisfythestructurethatPythonexpectstosee.WhenweobservetheerrorgivenbyPython,italsotells
ustheplacewhereitdetectedtheerroraswell.Sowestartdebuggingourprogramfromthatline.
Oncarefulobservation,weseethatthesinglelogicallinehasbeensplitintotwophysicallinesbutwe
havenotspecifiedthatthesetwophysicallinesbelongtogether.Basically,Pythonhasfoundtheaddition
operator( + )withoutanyoperandinthatlogicallineandhenceitdoesntknowhowtocontinue.
Rememberthatwecanspecifythatthelogicallinecontinuesinthenextphysicallinebytheuseofa
backslashattheendofthephysicalline.So,wemakethiscorrectiontoourprogram.Thiscorrectionof
theprogramwhenwefinderrorsiscalledbugfixing.

13.5.FourthVersion
Saveas backup_ver4.py :
importos
importtime

PYTHON

#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

http://www.swaroopch.com/notes/python/

104/165

1/4/2015

AByteofPython

#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=raw_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="zipr{0}{1}".format(target,
''.join(source))
#Runthebackup
print"Zipcommandis:"
printzip_command
print"Running:"
ifos.system(zip_command)==0:
print'Successfulbackupto',target
else:
print'BackupFAILED'

Output:
$pythonbackup_ver4.py
Enteracomment>addednewexamples
Zipcommandis:
zipr/Users/swa/backup/20140329/074122_added_new_examples.zip/Users/swa/notes
Running:
adding:Users/swa/notes/(stored0%)
adding:Users/swa/notes/blah1.txt(stored0%)
adding:Users/swa/notes/blah2.txt(stored0%)
adding:Users/swa/notes/blah3.txt(stored0%)
Successfulbackupto/Users/swa/backup/20140329/074122_added_new_examples.zip

HowItWorks

http://www.swaroopch.com/notes/python/

105/165

1/4/2015

AByteofPython

Thisprogramnowworks!Letusgothroughtheactualenhancementsthatwehadmadeinversion3.We
takeintheuserscommentsusingthe input functionandthencheckiftheuseractuallyentered
somethingbyfindingoutthelengthoftheinputusingthe len function.Iftheuserhasjustpressed
enter withoutenteringanything(maybeitwasjustaroutinebackupornospecialchangesweremade),

thenweproceedaswehavedonebefore.
However,ifacommentwassupplied,thenthisisattachedtothenameoftheziparchivejustbeforethe
.zip extension.Noticethatwearereplacingspacesinthecommentwithunderscoresthisisbecause

managingfilenameswithoutspacesismucheasier.

13.6.MoreRefinements
Thefourthversionisasatisfactorilyworkingscriptformostusers,butthereisalwaysroomfor
improvement.Forexample,youcanincludeaverbositylevelfortheprogramwhereyoucanspecifya
v optiontomakeyourprogrambecomemoretalkativeora q tomakeitquiet.

Anotherpossibleenhancementwouldbetoallowextrafilesanddirectoriestobepassedtothescriptat
thecommandline.Wecangetthesenamesfromthe sys.argv listandwecanaddthemtoour
source listusingthe extend methodprovidedbythe list class.

Themostimportantrefinementwouldbetonotusethe os.system wayofcreatingarchivesandinstead


usingthezipfile (http://docs.python.org/2/library/zipfile.html)ortarfile (http://docs.python.org/2/library/tarfile.html)
builtinmodulestocreatethesearchives.Theyarepartofthestandardlibraryandavailablealreadyfor
youtousewithoutexternaldependenciesonthezipprogramtobeavailableonyourcomputer.
However,Ihavebeenusingthe os.system wayofcreatingabackupintheaboveexamplespurelyfor
pedagogicalpurposes,sothattheexampleissimpleenoughtobeunderstoodbyeverybodybutreal
enoughtobeuseful.
Canyoutrywritingthefifthversionthatusesthezipfile (http://docs.python.org/2/library/zipfile.html)module
insteadofthe os.system call?

13.7.TheSoftwareDevelopmentProcess
Wehavenowgonethroughthevariousphasesintheprocessofwritingasoftware.Thesephasescanbe
summarisedasfollows:
1. What(Analysis)
2. How(Design)
3. DoIt(Implementation)
http://www.swaroopch.com/notes/python/

106/165

1/4/2015

AByteofPython

4. Test(TestingandDebugging)
5. Use(OperationorDeployment)
6. Maintain(Refinement)
Arecommendedwayofwritingprogramsistheprocedurewehavefollowedincreatingthebackup
script:Dotheanalysisanddesign.Startimplementingwithasimpleversion.Testanddebugit.Useitto
ensurethatitworksasexpected.Now,addanyfeaturesthatyouwantandcontinuetorepeattheDoIt
TestUsecycleasmanytimesasrequired.
Remember:

Softwareisgrown,notbuilt.
Billdehra (http://97things.oreilly.com/wiki/index.php/Great_software_is_not_built,_it_is_grown)

13.8.Summary
WehaveseenhowtocreateourownPythonprograms/scriptsandthevariousstagesinvolvedinwriting
suchprograms.Youmayfinditusefultocreateyourownprogramjustlikewedidinthischaptersothat
youbecomecomfortablewithPythonaswellasproblemsolving.
Next,wewilldiscussobjectorientedprogramming.

http://www.swaroopch.com/notes/python/

107/165

1/4/2015

AByteofPython

14.ObjectOrientedProgramming
Inalltheprogramswewrotetillnow,wehavedesignedourprogramaroundfunctionsi.e.blocksof
statementswhichmanipulatedata.Thisiscalledtheprocedureorientedwayofprogramming.Thereis
anotherwayoforganizingyourprogramwhichistocombinedataandfunctionalityandwrapitinside
somethingcalledanobject.Thisiscalledtheobjectorientedprogrammingparadigm.Mostofthetime
youcanuseproceduralprogramming,butwhenwritinglargeprogramsorhaveaproblemthatisbetter
suitedtothismethod,youcanuseobjectorientedprogrammingtechniques.
Classesandobjectsarethetwomainaspectsofobjectorientedprogramming.Aclasscreatesanewtype
whereobjectsareinstancesoftheclass.Ananalogyisthatyoucanhavevariablesoftype int which
translatestosayingthatvariablesthatstoreintegersarevariableswhichareinstances(objects)ofthe
int class.

NoteforStaticLanguageProgrammers
Notethatevenintegersaretreatedasobjects(ofthe int class).ThisisunlikeC++
andJava(beforeversion1.5)whereintegersareprimitivenativetypes.
NOTE

See help(int) formoredetailsontheclass.


C#andJava1.5programmerswillfindthissimilartotheboxingandunboxing
concept.

Objectscanstoredatausingordinaryvariablesthatbelongtotheobject.Variablesthatbelongtoan
objectorclassarereferredtoasfields.Objectscanalsohavefunctionalitybyusingfunctionsthatbelong
toaclass.Suchfunctionsarecalledmethodsoftheclass.Thisterminologyisimportantbecauseithelps
ustodifferentiatebetweenfunctionsandvariableswhichareindependentandthosewhichbelongtoa
classorobject.Collectively,thefieldsandmethodscanbereferredtoastheattributesofthatclass.
Fieldsareoftwotypestheycanbelongtoeachinstance/objectoftheclassortheycanbelongtothe
classitself.Theyarecalledinstancevariablesandclassvariablesrespectively.
Aclassiscreatedusingthe class keyword.Thefieldsandmethodsoftheclassarelistedinanindented
block.

14.1.Theself

http://www.swaroopch.com/notes/python/

108/165

1/4/2015

AByteofPython

Classmethodshaveonlyonespecificdifferencefromordinaryfunctionstheymusthaveanextrafirst
namethathastobeaddedtothebeginningoftheparameterlist,butyoudonotgiveavalueforthis
parameterwhenyoucallthemethod,Pythonwillprovideit.Thisparticularvariablereferstotheobject
itself,andbyconvention,itisgiventhename self .
Although,youcangiveanynameforthisparameter,itisstronglyrecommendedthatyouusethename
self anyothernameisdefinitelyfrownedupon.Therearemanyadvantagestousingastandardname

anyreaderofyourprogramwillimmediatelyrecognizeitandevenspecializedIDEs(Integrated
DevelopmentEnvironments)canhelpyouifyouuse self .
NoteforC++/Java/C#Programmers
NOTE

The self inPythonisequivalenttothe this pointerinC++andthe this


referenceinJavaandC#.

YoumustbewonderinghowPythongivesthevaluefor self andwhyyoudontneedtogiveavalue


forit.Anexamplewillmakethisclear.Sayyouhaveaclasscalled MyClass andaninstanceofthis
classcalled myobject .Whenyoucallamethodofthisobjectas myobject.method(arg1,arg2) ,
thisisautomaticallyconvertedbyPythoninto MyClass.method(myobject,arg1,arg2) thisisall
thespecial self isabout.
Thisalsomeansthatifyouhaveamethodwhichtakesnoarguments,thenyoustillhavetohaveone
argumentthe self .

14.2.Classes
Thesimplestclasspossibleisshowninthefollowingexample(saveas oop_simplestclass.py ).
classPerson:
pass#Anemptyblock

PYTHON

p=Person()
print(p)

Output:
$pythonoop_simplestclass.py
<__main__.Personinstanceat0x10171f518>

HowItWorks
http://www.swaroopch.com/notes/python/

109/165

1/4/2015

AByteofPython

Wecreateanewclassusingthe class statementandthenameoftheclass.Thisisfollowedbyan


indentedblockofstatementswhichformthebodyoftheclass.Inthiscase,wehaveanemptyblock
whichisindicatedusingthe pass statement.
Next,wecreateanobject/instanceofthisclassusingthenameoftheclassfollowedbyapairof
parentheses.(Wewilllearnmoreaboutinstantiationinthenextsection).Forourverification,weconfirm
thetypeofthevariablebysimplyprintingit.Ittellsusthatwehaveaninstanceofthe Person classin
the main module.
Noticethattheaddressofthecomputermemorywhereyourobjectisstoredisalsoprinted.Theaddress
willhaveadifferentvalueonyourcomputersincePythoncanstoretheobjectwhereveritfindsspace.

14.3.Methods
Wehavealreadydiscussedthatclasses/objectscanhavemethodsjustlikefunctionsexceptthatwehave
anextra self variable.Wewillnowseeanexample(saveas oop_method.py ).
classPerson:
defsay_hi(self):
print('Hello,howareyou?')

PYTHON

p=Person()
p.say_hi()
#Theprevious2linescanalsobewrittenas
#Person().say_hi()

Output:
$pythonoop_method.py
Hello,howareyou?

HowItWorks
Hereweseethe self inaction.Noticethatthe say_hi methodtakesnoparametersbutstillhasthe
self inthefunctiondefinition.

14.4.The init method


TherearemanymethodnameswhichhavespecialsignificanceinPythonclasses.Wewillseethe
significanceofthe init methodnow.

http://www.swaroopch.com/notes/python/

110/165

1/4/2015

AByteofPython

The init methodisrunassoonasanobjectofaclassisinstantiated.Themethodisusefultodoany


initializationyouwanttodowithyourobject.Noticethedoubleunderscoresbothatthebeginningand
attheendofthename.
Example(saveas oop_init.py ):
classPerson:
def__init__(self,name):
self.name=name
defsay_hi(self):
print'Hello,mynameis',self.name

PYTHON

p=Person('Swaroop')
p.say_hi()
#Theprevious2linescanalsobewrittenas
#Person('Swaroop').say_hi()

Output:
$pythonoop_init.py
Hello,mynameisSwaroop

HowItWorks
Here,wedefinethe init methodastakingaparameter name (alongwiththeusual self ).Here,we
justcreateanewfieldalsocalled name .Noticethesearetwodifferentvariableseventhoughtheyare
bothcalled'name'.Thereisnoproblembecausethedottednotation self.name meansthatthereis
somethingcalled"name"thatispartoftheobjectcalled"self"andtheother name isalocalvariable.
Sinceweexplicitlyindicatewhichnamewearereferringto,thereisnoconfusion.
Mostimportantly,noticethatwedonotexplicitlycallthe init methodbutpasstheargumentsinthe
parenthesesfollowingtheclassnamewhencreatinganewinstanceoftheclass.Thisisthespecial
significanceofthismethod.
Now,weareabletousethe self.name fieldinourmethodswhichisdemonstratedinthe sayHi
method.

14.5.ClassAndObjectVariables
Wehavealreadydiscussedthefunctionalitypartofclassesandobjects(i.e.methods),nowletuslearn
aboutthedatapart.Thedatapart,i.e.fields,arenothingbutordinaryvariablesthatareboundtothe
namespacesoftheclassesandobjects.Thismeansthatthesenamesarevalidwithinthecontextofthese
http://www.swaroopch.com/notes/python/

111/165

1/4/2015

AByteofPython

classesandobjectsonly.Thatswhytheyarecallednamespaces.
Therearetwotypesoffieldsclassvariablesandobjectvariableswhichareclassifieddependingon
whethertheclassortheobjectownsthevariablesrespectively.
Classvariablesaresharedtheycanbeaccessedbyallinstancesofthatclass.Thereisonlyonecopyof
theclassvariableandwhenanyoneobjectmakesachangetoaclassvariable,thatchangewillbeseen
byalltheotherinstances.
Objectvariablesareownedbyeachindividualobject/instanceoftheclass.Inthiscase,eachobjecthas
itsowncopyofthefieldi.e.theyarenotsharedandarenotrelatedinanywaytothefieldbythesame
nameinadifferentinstance.Anexamplewillmakethiseasytounderstand(saveas oop_objvar.py ):
classRobot:
"""Representsarobot,withaname."""

PYTHON

#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):
http://www.swaroopch.com/notes/python/

112/165

1/4/2015

AByteofPython

"""Printsthecurrentpopulation."""
print"Wehave{:d}robots.".format(cls.population)

droid1=Robot("R2D2")
droid1.say_hi()
Robot.how_many()
droid2=Robot("C3PO")
droid2.say_hi()
Robot.how_many()
print"\nRobotscandosomeworkhere.\n"
print"Robotshavefinishedtheirwork.Solet'sdestroythem."
droid1.die()
droid2.die()
Robot.how_many()

Output:
$pythonoop_objvar.py
(InitializingR2D2)
Greetings,mymasterscallmeR2D2.
Wehave1robots.
(InitializingC3PO)
Greetings,mymasterscallmeC3PO.
Wehave2robots.
Robotscandosomeworkhere.
Robotshavefinishedtheirwork.Solet'sdestroythem.
R2D2isbeingdestroyed!
Therearestill1robotsworking.
C3POisbeingdestroyed!
C3POwasthelastone.
Wehave0robots.

HowItWorks
Thisisalongexamplebuthelpsdemonstratethenatureofclassandobjectvariables.Here,
population belongstothe Robot classandhenceisaclassvariable.The name variablebelongsto

theobject(itisassignedusing self )andhenceisanobjectvariable.


Thus,werefertothe population classvariableas Robot.population andnotas
self.population .Werefertotheobjectvariable name using self.name notationinthemethods

ofthatobject.Rememberthissimpledifferencebetweenclassandobjectvariables.Alsonotethatan
http://www.swaroopch.com/notes/python/

113/165

1/4/2015

AByteofPython

objectvariablewiththesamenameasaclassvariablewillhidetheclassvariable!
Insteadof Robot.population ,wecouldhavealsousedself.__class__.populationbecauseeveryobject
referstoitsclassviatheself.__class__attribute.
The how_many isactuallyamethodthatbelongstotheclassandnottotheobject.Thismeanswecan
defineitaseithera classmethod ora staticmethod dependingonwhetherweneedtoknowwhich
classwearepartof.Sincewerefertoaclassvariable,letsuse classmethod .
Wehavemarkedthe how_many methodasaclassmethodusingadecorator.
Decoratorscanbeimaginedtobeashortcuttocallingawrapperfunction,soapplyingthe
@classmethod decoratorissameascalling:
how_many=classmethod(how_many)

PYTHON

Observethatthe init methodisusedtoinitializethe Robot instancewithaname.Inthismethod,we


increasethe population countby1sincewehaveonemorerobotbeingadded.Alsoobservethatthe
valuesof self.name isspecifictoeachobjectwhichindicatesthenatureofobjectvariables.
Remember,thatyoumustrefertothevariablesandmethodsofthesameobjectusingthe self only.
Thisiscalledanattributereference.
Inthisprogram,wealsoseetheuseofdocstringsforclassesaswellasmethods.Wecanaccesstheclass
docstringatruntimeusing Robot.doc andthemethoddocstringas Robot.say_hi.doc
Inthe die method,wesimplydecreasethe Robot.population countby1.
Allclassmembersarepublic.Oneexception:Ifyouusedatamemberswithnamesusingthedouble
underscoreprefixsuchas __privatevar ,Pythonusesnamemanglingtoeffectivelymakeitaprivate
variable.
Thus,theconventionfollowedisthatanyvariablethatistobeusedonlywithintheclassorobjectshould
beginwithanunderscoreandallothernamesarepublicandcanbeusedbyotherclasses/objects.
RememberthatthisisonlyaconventionandisnotenforcedbyPython(exceptforthedoubleunderscore
prefix).
NoteforC++/Java/C#Programmers

http://www.swaroopch.com/notes/python/

114/165

1/4/2015

NOTE

AByteofPython

Allclassmembers(includingthedatamembers)arepublicandallthemethodsare
virtualinPython.

14.6.Inheritance
Oneofthemajorbenefitsofobjectorientedprogrammingisreuseofcodeandoneofthewaysthisis
achievedisthroughtheinheritancemechanism.Inheritancecanbebestimaginedasimplementinga
typeandsubtyperelationshipbetweenclasses.
Supposeyouwanttowriteaprogramwhichhastokeeptrackoftheteachersandstudentsinacollege.
Theyhavesomecommoncharacteristicssuchasname,ageandaddress.Theyalsohavespecific
characteristicssuchassalary,coursesandleavesforteachersand,marksandfeesforstudents.
Youcancreatetwoindependentclassesforeachtypeandprocessthembutaddinganewcommon
characteristicwouldmeanaddingtobothoftheseindependentclasses.Thisquicklybecomesunwieldy.
Abetterwaywouldbetocreateacommonclasscalled SchoolMember andthenhavetheteacherand
studentclassesinheritfromthisclassi.e.theywillbecomesubtypesofthistype(class)andthenwecan
addspecificcharacteristicstothesesubtypes.
Therearemanyadvantagestothisapproach.Ifweadd/changeanyfunctionalityin SchoolMember ,this
isautomaticallyreflectedinthesubtypesaswell.Forexample,youcanaddanewIDcardfieldforboth
teachersandstudentsbysimplyaddingittotheSchoolMemberclass.However,changesinthesubtypes
donotaffectothersubtypes.Anotheradvantageisthatifyoucanrefertoateacherorstudentobjectasa
SchoolMember objectwhichcouldbeusefulinsomesituationssuchascountingofthenumberof

schoolmembers.Thisiscalledpolymorphismwhereasubtypecanbesubstitutedinanysituation
whereaparenttypeisexpectedi.e.theobjectcanbetreatedasaninstanceoftheparentclass.
Alsoobservethatwereusethecodeoftheparentclassandwedonotneedtorepeatitinthedifferent
classesaswewouldhavehadtoincasewehadusedindependentclasses.
The SchoolMember classinthissituationisknownasthebaseclassorthesuperclass.The Teacher
and Student classesarecalledthederivedclassesorsubclasses.
Wewillnowseethisexampleasaprogram(saveas oop_subclass.py ):

http://www.swaroopch.com/notes/python/

115/165

1/4/2015

AByteofPython

classSchoolMember:
'''Representsanyschoolmember.'''
def__init__(self,name,age):
self.name=name
self.age=age
print'(InitializedSchoolMember:{})'.format(self.name)

PYTHON

deftell(self):
'''Tellmydetails.'''
print'Name:"{}"Age:"{}"'.format(self.name,self.age),
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:

http://www.swaroopch.com/notes/python/

116/165

1/4/2015

AByteofPython

$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,wespecifythebaseclassnamesinatuplefollowingtheclassnameintheclass
definition.Next,weobservethatthe init methodofthebaseclassisexplicitlycalledusingthe self
variablesothatwecaninitializethebaseclasspartoftheobject.Thisisveryimportanttoremember
Pythondoesnotautomaticallycalltheconstructorofthebaseclass,youhavetoexplicitlycallityourself.
Wealsoobservethatwecancallmethodsofthebaseclassbyprefixingtheclassnametothemethodcall
andthenpassinthe self variablealongwithanyarguments.
Noticethatwecantreatinstancesof Teacher or Student asjustinstancesofthe SchoolMember
whenweusethe tell methodofthe SchoolMember class.
Also,observethatthe tell methodofthesubtypeiscalledandnotthe tell methodofthe
SchoolMember class.OnewaytounderstandthisisthatPythonalwaysstartslookingformethodsin

theactualtype,whichinthiscaseitdoes.Ifitcouldnotfindthemethod,itstartslookingatthemethods
belongingtoitsbaseclassesonebyoneintheordertheyarespecifiedinthetupleintheclassdefinition.
Anoteonterminologyifmorethanoneclassislistedintheinheritancetuple,thenitiscalledmultiple
inheritance.
Thetrailingcommaisusedattheendofthe print statementinthesuperclasss tell() methodto
printalineandallowthenextprinttocontinueonthesameline.Thisisatricktomake print notprint
a \n (newline)symbolattheendoftheprinting.

14.7.Summary
Wehavenowexploredthevariousaspectsofclassesandobjectsaswellasthevariousterminologies
associatedwithit.Wehavealsoseenthebenefitsandpitfallsofobjectorientedprogramming.Pythonis
highlyobjectorientedandunderstandingtheseconceptscarefullywillhelpyoualotinthelongrun.
Next,wewilllearnhowtodealwithinput/outputandhowtoaccessfilesinPython.

http://www.swaroopch.com/notes/python/

117/165

1/4/2015

AByteofPython

15.InputandOutput
Therewillbesituationswhereyourprogramhastointeractwiththeuser.Forexample,youwouldwant
totakeinputfromtheuserandthenprintsomeresultsback.Wecanachievethisusingthe
raw_input() functionand print statementrespectively.

Foroutput,wecanalsousethevariousmethodsofthe str (string)class.Forexample,youcanusethe


rjust methodtogetastringwhichisrightjustifiedtoaspecifiedwidth.See help(str) formore

details.
Anothercommontypeofinput/outputisdealingwithfiles.Theabilitytocreate,readandwritefilesis
essentialtomanyprogramsandwewillexplorethisaspectinthischapter.

15.1.Inputfromuser
Savethisprogramas io_input.py :
defreverse(text):
returntext[::1]

PYTHON

defis_palindrome(text):
returntext==reverse(text)
something=raw_input("Entertext:")
ifis_palindrome(something):
print"Yes,itisapalindrome"
else:
print"No,itisnotapalindrome"

Output:
$pythonio_input.py
Entertext:sir
No,itisnotapalindrome
$pythonio_input.py
Entertext:madam
Yes,itisapalindrome
$pythonio_input.py
Entertext:racecar
Yes,itisapalindrome

HowItWorks
http://www.swaroopch.com/notes/python/

118/165

1/4/2015

AByteofPython

Weusetheslicingfeaturetoreversethetext.Wevealreadyseenhowwecanmakeslicesfrom
sequencesusingthe seq[a:b] codestartingfromposition a toposition b .Wecanalsoprovideathird
argumentthatdeterminesthestepbywhichtheslicingisdone.Thedefaultstepis 1 becauseofwhichit
returnsacontinuouspartofthetext.Givinganegativestep,i.e., 1 willreturnthetextinreverse.
The raw_input() functiontakesastringasargumentanddisplaysittotheuser.Thenitwaitsforthe
usertotypesomethingandpressthereturnkey.Oncetheuserhasenteredandpressedthereturnkey,the
raw_input() functionwillthenreturnthattexttheuserhasentered.

Wetakethattextandreverseit.Iftheoriginaltextandreversedtextareequal,thenthetextisa
palindrome (http://en.wiktionary.org/wiki/palindrome).

15.1.1.Homeworkexercise
Checkingwhetheratextisapalindromeshouldalsoignorepunctuation,spacesandcase.Forexample,
"Risetovote,sir."isalsoapalindromebutourcurrentprogramdoesntsayitis.Canyouimprovethe
aboveprogramtorecognizethispalindrome?
Ifyouneedahint,theideaisthat[2]

15.2.Files
Youcanopenandusefilesforreadingorwritingbycreatinganobjectofthe file classandusingits
read , readline or write methodsappropriatelytoreadfromorwritetothefile.Theabilitytoread

orwritetothefiledependsonthemodeyouhavespecifiedforthefileopening.Thenfinally,whenyou
arefinishedwiththefile,youcallthe close methodtotellPythonthatwearedoneusingthefile.
Example(saveas io_using_file.py ):

http://www.swaroopch.com/notes/python/

119/165

1/4/2015

poem='''\
Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!
'''

AByteofPython
PYTHON

#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.
printline,
#closethefile
f.close()

Output:
$pythonio_using_file.py
Programmingisfun
Whentheworkisdone
ifyouwannamakeyourworkalsofun:
usePython!

HowItWorks
First,openafilebyusingthebuiltin open functionandspecifyingthenameofthefileandthemodein
whichwewanttoopenthefile.Themodecanbeareadmode( 'r' ),writemode( 'w' )orappend
mode( 'a' ).Wecanalsospecifywhetherwearereading,writing,orappendingintextmode( 't' )or
binarymode( 'b' ).Thereareactuallymanymoremodesavailableand help(open) willgiveyou
moredetailsaboutthem.Bydefault, open() considersthefiletobea'textfileandopensitin'read
mode.

http://www.swaroopch.com/notes/python/

120/165

1/4/2015

AByteofPython

Inourexample,wefirstopenthefileinwritetextmodeandusethe write methodofthefileobjectto


writetothefileandthenwefinally close thefile.
Next,weopenthesamefileagainforreading.Wedontneedtospecifyamodebecause'readtextfile'is
thedefaultmode.Wereadineachlineofthefileusingthe readline methodinaloop.Thismethod
returnsacompletelineincludingthenewlinecharacterattheendoftheline.Whenanemptystringis
returned,itmeansthatwehavereachedtheendofthefileandwe'break'outoftheloop.
Intheend,wefinally close thefile.
Now,checkthecontentsofthe poem.txt filetoconfirmthattheprogramhasindeedwrittentoand
readfromthatfile.

15.3.Pickle
Pythonprovidesastandardmodulecalled pickle usingwhichyoucanstoreanyplainPythonobjectin
afileandthengetitbacklater.Thisiscalledstoringtheobjectpersistently.
Example(saveas io_pickle.py ):
importpickle

PYTHON

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

Output:

http://www.swaroopch.com/notes/python/

121/165

1/4/2015

AByteofPython

$pythonio_pickle.py
['apple','mango','carrot']

HowItWorks
Tostoreanobjectinafile,wehavetofirst open thefileinwritebinarymodeandthencallthe dump
functionofthe pickle module.Thisprocessiscalledpickling.
Next,weretrievetheobjectusingthe load functionofthe pickle modulewhichreturnstheobject.
Thisprocessiscalledunpickling.

15.4.Unicode
Sofar,whenwehavebeenwritingandusingstrings,orreadingandwritingtoafile,wehaveused
simpleEnglishcharactersonly.IfwewanttobeabletoreadandwriteothernonEnglishlanguages,we
needtousethe unicode type,anditallstartswiththecharacter u :
>>>"helloworld"
'helloworld'
>>>type("helloworld")
<type'str'>
>>>u"helloworld"
u'helloworld'
>>>type(u"helloworld")
<type'unicode'>

Weusethe unicode typeinsteadof strings tomakesurethatwehandlenonEnglishlanguagesin


ourprograms.However,whenwereadorwritetoafileorwhenwetalktoothercomputersonthe
Internet,weneedtoconvertourunicodestringsintoaformatthatcanbesentandreceived,andthat
formatiscalled"UTF8".Wecanreadandwriteinthatformat,usingasimplekeywordargumenttoour
standard open function:
#encoding=utf8
importio

PYTHON

f=io.open("abc.txt","wt",encoding="utf8")
f.write(u"ImaginenonEnglishlanguagehere")
f.close()
text=io.open("abc.txt",encoding="utf8").read()
printtext

HowItWorks
http://www.swaroopch.com/notes/python/

122/165

1/4/2015

AByteofPython

Youcanignorethe import statementfornow,wellexplorethatindetailinthemoduleschapter.


WheneverwewriteaprogramthatusesUnicodeliteralslikewehaveusedabove,wehavetomakesure
thatPythonitselfistoldthatourprogramusesUTF8,andwehavetoput #encoding=utf8
commentatthetopofourprogram.
Weuse io.open andprovidethe"encoding"and"decoding"argumenttotellPythonthatweareusing
unicode,andinfact,wehavetopassinastringintheformof u"" tomakeitclearthatweareusing
Unicodestrings.
Youshouldlearnmoreaboutthistopicbyreading:
"TheAbsoluteMinimumEverySoftwareDeveloperAbsolutely,PositivelyMustKnowAbout
UnicodeandCharacterSets" (http://www.joelonsoftware.com/articles/Unicode.html)
PythonUnicodeHowto (http://docs.python.org/2/howto/unicode.html)
PragmaticUnicodetalkbyNatBatchelder (http://nedbatchelder.com/text/unipain.html)

15.5.Summary
Wehavediscussedvarioustypesofinput/output,aboutfilehandling,aboutthepicklemoduleandabout
Unicode.
Next,wewillexploretheconceptofexceptions.

http://www.swaroopch.com/notes/python/

123/165

1/4/2015

AByteofPython

16.Exceptions
Exceptionsoccurwhenexceptionalsituationsoccurinyourprogram.Forexample,whatifyouaregoing
toreadafileandthefiledoesnotexist?Orwhatifyouaccidentallydeleteditwhentheprogramwas
running?Suchsituationsarehandledusingexceptions.
Similarly,whatifyourprogramhadsomeinvalidstatements?ThisishandledbyPythonwhichraisesits
handsandtellsyouthereisanerror.

16.1.Errors
Considerasimple print functioncall.Whatifwemisspelt print as Print ?Notethecapitalization.
Inthiscase,Pythonraisesasyntaxerror.
>>>Print"HelloWorld"
File"<stdin>",line1
Print"HelloWorld"
^
SyntaxError:invalidsyntax
>>>print"HelloWorld"
HelloWorld

Observethata SyntaxError israisedandalsothelocationwheretheerrorwasdetectedisprinted.This


iswhatanerrorhandlerforthiserrordoes.

16.2.Exceptions
Wewilltrytoreadinputfromtheuser.Press ctrld andseewhathappens.
>>>s=raw_input('Entersomething>')
Entersomething>Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
EOFError

Pythonraisesanerrorcalled EOFError whichbasicallymeansitfoundanendoffilesymbol(whichis


representedby ctrld )whenitdidnotexpecttoseeit.

16.3.HandlingExceptions
Wecanhandleexceptionsusingthe try..except statement.Webasicallyputourusualstatements
withinthetryblockandputallourerrorhandlersintheexceptblock.

http://www.swaroopch.com/notes/python/

124/165

1/4/2015

AByteofPython

Example(saveas exceptions_handle.py ):
try:
text=raw_input('Entersomething>')
exceptEOFError:
print'WhydidyoudoanEOFonme?'
exceptKeyboardInterrupt:
print'Youcancelledtheoperation.'
else:
print'Youentered{}'.format(text)

PYTHON

Output:
#Pressctrl+d
$pythonexceptions_handle.py
Entersomething>WhydidyoudoanEOFonme?
#Pressctrl+c
$pythonexceptions_handle.py
Entersomething>^CYoucancelledtheoperation.
$pythonexceptions_handle.py
Entersomething>Noexceptions
YouenteredNoexceptions

HowItWorks
Weputallthestatementsthatmightraiseexceptions/errorsinsidethe try blockandthenputhandlers
fortheappropriateerrors/exceptionsinthe except clause/block.The except clausecanhandlea
singlespecifiederrororexception,oraparenthesizedlistoferrors/exceptions.Ifnonamesoferrorsor
exceptionsaresupplied,itwillhandleallerrorsandexceptions.
Notethattherehastobeatleastone except clauseassociatedwithevery try clause.Otherwise,
whatsthepointofhavingatryblock?
Ifanyerrororexceptionisnothandled,thenthedefaultPythonhandleriscalledwhichjuststopsthe
executionoftheprogramandprintsanerrormessage.Wehavealreadyseenthisinactionabove.
Youcanalsohavean else clauseassociatedwitha try..except block.The else clauseis
executedifnoexceptionoccurs.
Inthenextexample,wewillalsoseehowtogettheexceptionobjectsothatwecanretrieveadditional
information.

http://www.swaroopch.com/notes/python/

125/165

1/4/2015

AByteofPython

16.4.RaisingExceptions
Youcanraiseexceptionsusingthe raise statementbyprovidingthenameoftheerror/exceptionand
theexceptionobjectthatistobethrown.
Theerrororexceptionthatyoucanraiseshouldbeaclasswhichdirectlyorindirectlymustbeaderived
classofthe Exception class.
Example(saveas exceptions_raise.py ):
classShortInputException(Exception):
'''Auserdefinedexceptionclass.'''
def__init__(self,length,atleast):
Exception.__init__(self)
self.length=length
self.atleast=atleast

PYTHON

try:
text=raw_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
Here,wearecreatingourownexceptiontype.Thisnewexceptiontypeiscalled
ShortInputException .Ithastwofields length whichisthelengthofthegiveninput,and
atleast whichistheminimumlengththattheprogramwasexpecting.
http://www.swaroopch.com/notes/python/

126/165

1/4/2015

AByteofPython

Inthe except clause,wementiontheclassoferrorwhichwillbestored as thevariablenametohold


thecorrespondingerror/exceptionobject.Thisisanalogoustoparametersandargumentsinafunction
call.Withinthisparticular except clause,weusethe length and atleast fieldsoftheexception
objecttoprintanappropriatemessagetotheuser.

16.5.TryFinally
Supposeyouarereadingafileinyourprogram.Howdoyouensurethatthefileobjectisclosedproperly
whetherornotanexceptionwasraised?Thiscanbedoneusingthe finally block.
Savethisprogramas exceptions_finally.py :
importsys
importtime

PYTHON

f=None
try:
f=open("poem.txt")
#Ourusualfilereadingidiom
whileTrue:
line=f.readline()
iflen(line)==0:
break
printline,
sys.stdout.flush()
print"Pressctrl+cnow"
#Tomakesureitrunsforawhile
time.sleep(2)
exceptIOError:
print"Couldnotfindfilepoem.txt"
exceptKeyboardInterrupt:
print"!!Youcancelledthereadingfromthefile."
finally:
iff:
f.close()
print"(Cleaningup:Closedthefile)"

Output:
$pythonexceptions_finally.py
Programmingisfun
Pressctrl+cnow
^C!!Youcancelledthereadingfromthefile.
(Cleaningup:Closedthefile)

HowItWorks
http://www.swaroopch.com/notes/python/

127/165

1/4/2015

AByteofPython

Wedotheusualfilereadingstuff,butwehavearbitrarilyintroducedsleepingfor2secondsafterprinting
eachlineusingthe time.sleep functionsothattheprogramrunsslowly(Pythonisveryfastby
nature).Whentheprogramisstillrunning,press ctrl+c tointerrupt/canceltheprogram.
Observethatthe KeyboardInterrupt exceptionisthrownandtheprogramquits.However,beforethe
programexits,thefinallyclauseisexecutedandthefileobjectisalwaysclosed.
Notethatweuse sys.stdout.flush() after print sothatitprintstothescreenimmediately.

16.6.Thewithstatement
Acquiringaresourceinthe try blockandsubsequentlyreleasingtheresourceinthe finally blockis
acommonpattern.Hence,thereisalsoa with statementthatenablesthistobedoneinacleanmanner:
Saveas exceptions_using_with.py :
withopen("poem.txt")asf:
forlineinf:
printline,

PYTHON

HowItWorks
Theoutputshouldbesameasthepreviousexample.Thedifferencehereisthatweareusingthe open
functionwiththe with statementweleavetheclosingofthefiletobedoneautomaticallyby with
open .

Whathappensbehindthescenesisthatthereisaprotocolusedbythe with statement.Itfetchesthe


objectreturnedbythe open statement,letscallit"thefile"inthiscase.
Italwayscallsthe thefile.enter functionbeforestartingtheblockofcodeunderitandalwayscalls
thefile.exit afterfinishingtheblockofcode.

Sothecodethatwewouldhavewrittenina finally blockshouldbetakencareofautomaticallybythe


exit method.Thisiswhathelpsustoavoidhavingtouseexplicit try..finally statements

repeatedly.
Morediscussiononthistopicisbeyondscopeofthisbook,sopleasereferPEP343
(http://www.python.org/dev/peps/pep0343/)foracomprehensiveexplanation.

16.7.Summary

http://www.swaroopch.com/notes/python/

128/165

1/4/2015

AByteofPython

Wehavediscussedtheusageofthe try..except and try..finally statements.Wehaveseenhow


tocreateourownexceptiontypesandhowtoraiseexceptionsaswell.
Next,wewillexplorethePythonStandardLibrary.

http://www.swaroopch.com/notes/python/

129/165

1/4/2015

AByteofPython

17.StandardLibrary
ThePythonStandardLibrarycontainsahugenumberofusefulmodulesandispartofeverystandard
Pythoninstallation.ItisimportanttobecomefamiliarwiththePythonStandardLibrarysincemany
problemscanbesolvedquicklyifyouarefamiliarwiththerangeofthingsthattheselibrariescando.
Wewillexploresomeofthecommonlyusedmodulesinthislibrary.Youcanfindcompletedetailsforall
ofthemodulesinthePythonStandardLibraryinthe'LibraryReference'section
(http://docs.python.org/2/library/)ofthedocumentationthatcomeswithyourPythoninstallation.

Letusexploreafewusefulmodules.
Ifyoufindthetopicsinthischaptertooadvanced,youmayskipthischapter.
CAUTION

However,Ihighlyrecommendcomingbacktothischapterwhenyouaremore
comfortablewithprogrammingusingPython.

17.1.sysmodule
The sys modulecontainssystemspecificfunctionality.Wehavealreadyseenthatthe sys.argv list
containsthecommandlinearguments.
SupposewewanttochecktheversionofthePythonsoftwarebeingused,the sys modulegivesusthat
information.
$python
>>>importsys
>>>sys.version_info
sys.version_info(major=2,minor=7,micro=6,releaselevel='final',serial=0)
>>>sys.version_info.major==2
True

HowItWorks
The sys modulehasa version_info tuplethatgivesustheversioninformation.Thefirstentryisthe
majorversion.Wecanpulloutthisinformationtouseit.

17.2.loggingmodule
Whatifyouwantedtohavesomedebuggingmessagesorimportantmessagestobestoredsomewhereso
thatyoucancheckwhetheryourprogramhasbeenrunningasyouwouldexpectit?Howdoyou"store
somewhere"thesemessages?Thiscanbeachievedusingthe logging module.

http://www.swaroopch.com/notes/python/

130/165

1/4/2015

AByteofPython

Saveas stdlib_logging.py :
importos,platform,logging

PYTHON

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
2014032909:27:36,660:DEBUG:Startoftheprogram
2014032909:27:36,660:INFO:Doingsomething
2014032909:27:36,660:WARNING:Dyingnow

Ifyoudonothavethe cat command,thenyoucanjustopenthe test.log fileinatexteditor.


HowItWorks
Weusethreemodulesfromthestandardlibrarythe os moduleforinteractingwiththeoperating
system,the platform moduleforinformationabouttheplatformi.e.theoperatingsystemandthe
logging moduletologinformation.

First,wecheckwhichoperatingsystemweareusingbycheckingthestringreturnedby
platform.platform() (formoreinformation,see importplatform;help(platform) ).Ifitis

Windows,wefigureoutthehomedrive,thehomefolderandthefilenamewherewewanttostorethe
http://www.swaroopch.com/notes/python/

131/165

1/4/2015

AByteofPython

information.Puttingthesethreepartstogether,wegetthefulllocationofthefile.Forotherplatforms,we
needtoknowjustthehomefolderoftheuserandwegetthefulllocationofthefile.
Weusethe os.path.join() functiontoputthesethreepartsofthelocationtogether.Thereasontouse
aspecialfunctionratherthanjustaddingthestringstogetherisbecausethisfunctionwillensurethefull
locationmatchestheformatexpectedbytheoperatingsystem.
Weconfigurethe logging moduletowriteallthemessagesinaparticularformattothefilewehave
specified.
Finally,wecanputmessagesthatareeithermeantfordebugging,information,warningorevencritical
messages.Oncetheprogramhasrun,wecancheckthisfileandwewillknowwhathappenedinthe
program,eventhoughnoinformationwasdisplayedtotheuserrunningtheprogram.

17.3.ModuleoftheWeekSeries
Thereismuchmoretobeexploredinthestandardlibrarysuchasdebugging
(http://docs.python.org/2/library/pdb.html),handlingcommandlineoptions
(http://docs.python.org/2/library/argparse.html),regularexpressions (http://docs.python.org/2/library/re.html)andso

on.
ThebestwaytofurtherexplorethestandardlibraryistoreadDougHellmannsexcellentPythonModule
oftheWeek (http://pymotw.com/2/contents.html)series(alsoavailableasabook (http://amzn.com/0321767349))
andreadingthePythondocumentation (http://docs.python.org/2/).

17.4.Summary
WehaveexploredsomeofthefunctionalityofmanymodulesinthePythonStandardLibrary.Itishighly
recommendedtobrowsethroughthePythonStandardLibrarydocumentation
(http://docs.python.org/2/library/)togetanideaofallthemodulesthatareavailable.

Next,wewillcovervariousaspectsofPythonthatwillmakeourtourofPythonmorecomplete.

http://www.swaroopch.com/notes/python/

132/165

1/4/2015

AByteofPython

18.More
SofarwehavecoveredamajorityofthevariousaspectsofPythonthatyouwilluse.Inthischapter,we
willcoversomemoreaspectsthatwillmakeourknowledgeofPythonmorewellrounded.

18.1.Passingtuplesaround
Everwishedyoucouldreturntwodifferentvaluesfromafunction?Youcan.Allyouhavetodoisusea
tuple.
>>>defget_error_details():
...return(2,'details')
...
>>>errnum,errstr=get_error_details()
>>>errnum
2
>>>errstr
'details'

Noticethattheusageof a,b=<someexpression> interpretstheresultoftheexpressionasatuple


withtwovalues.
ThisalsomeansthefastestwaytoswaptwovariablesinPythonis:
>>>a=5;b=8
>>>a,b
(5,8)
>>>a,b=b,a
>>>a,b
(8,5)

18.2.SpecialMethods
Therearecertainmethodssuchasthe init and del methodswhichhavespecialsignificancein
classes.
Specialmethodsareusedtomimiccertainbehaviorsofbuiltintypes.Forexample,ifyouwanttouse
the x[key] indexingoperationforyourclass(justlikeyouuseitforlistsandtuples),thenallyouhave
todoisimplementthe getitem() methodandyourjobisdone.Ifyouthinkaboutit,thisiswhat
Pythondoesforthe list classitself!
Someusefulspecialmethodsarelistedinthefollowingtable.Ifyouwanttoknowaboutallthespecial
methods,seethemanual (http://docs.python.org/2/reference/datamodel.html#specialmethodnames).
http://www.swaroopch.com/notes/python/

133/165

1/4/2015

AByteofPython

init(self,
)

Thismethodiscalledjustbeforethenewlycreatedobjectisreturnedforusage.
del(self)

Calledjustbeforetheobjectisdestroyed(whichhasunpredictabletiming,soavoidusingthis)
str(self)

Calledwhenweusethe print statementorwhen str() isused.


lt(self,other)

Calledwhenthelessthanoperator(<)isused.Similarly,therearespecialmethodsforalltheoperators
(+,>,etc.)
getitem(self,key)

Calledwhen x[key] indexingoperationisused.


len(self)

Calledwhenthebuiltin len() functionisusedforthesequenceobject.

18.3.SingleStatementBlocks
Wehaveseenthateachblockofstatementsissetapartfromtherestbyitsownindentationlevel.Well,
thereisonecaveat.Ifyourblockofstatementscontainsonlyonesinglestatement,thenyoucanspecifyit
onthesamelineof,say,aconditionalstatementorloopingstatement.Thefollowingexampleshould
makethisclear:
>>>flag=True
>>>ifflag:print'Yes'
...
Yes

Noticethatthesinglestatementisusedinplaceandnotasaseparateblock.Although,youcanusethis
formakingyourprogramsmaller,Istronglyrecommendavoidingthisshortcutmethod,exceptforerror
checking,mainlybecauseitwillbemucheasiertoaddanextrastatementifyouareusingproper
indentation.

18.4.LambdaForms

http://www.swaroopch.com/notes/python/

134/165

1/4/2015

AByteofPython

A lambda statementisusedtocreatenewfunctionobjects.Essentially,the lambda takesaparameter


followedbyasingleexpressiononlywhichbecomesthebodyofthefunctionandthevalueofthis
expressionisreturnedbythenewfunction.
Example(saveas more_lambda.py ):
points=[{'x':2,'y':3},
{'x':4,'y':1}]
points.sort(key=lambdai:i['y'])
printpoints

PYTHON

Output:
$pythonmore_lambda.py
[{'y':1,'x':4},{'y':3,'x':2}]

HowItWorks
Noticethatthe sort methodofa list cantakea key parameterwhichdetermineshowthelistis
sorted(usuallyweknowonlyaboutascendingordescendingorder).Inourcase,wewanttodoacustom
sort,andforthatweneedtowriteafunctionbutinsteadofwritingaseparate def blockforafunction
thatwillgetusedinonlythisoneplace,weusealambdaexpressiontocreateanewfunction.

18.5.ListComprehension
Listcomprehensionsareusedtoderiveanewlistfromanexistinglist.Supposeyouhavealistof
numbersandyouwanttogetacorrespondinglistwithallthenumbersmultipliedby2onlywhenthe
numberitselfisgreaterthan2.Listcomprehensionsareidealforsuchsituations.
Example(saveas more_list_comprehension.py ):
listone=[2,3,4]
listtwo=[2*iforiinlistoneifi>2]
printlisttwo

PYTHON

Output:
$pythonmore_list_comprehension.py
[6,8]

HowItWorks
http://www.swaroopch.com/notes/python/

135/165

1/4/2015

AByteofPython

Here,wederiveanewlistbyspecifyingthemanipulationtobedone(2*i)whensomeconditionis
satisfied( ifi>2 ).Notethattheoriginallistremainsunmodified.
Theadvantageofusinglistcomprehensionsisthatitreducestheamountofboilerplatecoderequired
whenweuseloopstoprocesseachelementofalistandstoreitinanewlist.

18.6.ReceivingTuplesandDictionariesinFunctions
Thereisaspecialwayofreceivingparameterstoafunctionasatupleoradictionaryusingthe*or**
prefixrespectively.Thisisusefulwhentakingvariablenumberofargumentsinthefunction.
>>>defpowersum(power,*args):
...'''Returnthesumofeachargumentraisedtothespecifiedpower.'''
...total=0
...foriinargs:
...total+=pow(i,power)
...returntotal
...
>>>powersum(2,3,4)
25
>>>powersum(2,10)
100

Becausewehavea*prefixonthe args variable,allextraargumentspassedtothefunctionarestoredin


args asatuple.Ifa**prefixhadbeenusedinstead,theextraparameterswouldbeconsideredtobe

key/valuepairsofadictionary.

18.7.Theassertstatement
The assert statementisusedtoassertthatsomethingistrue.Forexample,ifyouareverysurethatyou
willhaveatleastoneelementinalistyouareusingandwanttocheckthis,andraiseanerrorifitisnot
true,then assert statementisidealinthissituation.Whentheassertstatementfails,an
AssertionError israised.
>>>mylist=['item']
>>>assertlen(mylist)>=1
>>>mylist.pop()
'item'
>>>assertlen(mylist)>=1
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
AssertionError

http://www.swaroopch.com/notes/python/

136/165

1/4/2015

AByteofPython

The assert statementshouldbeusedjudiciously.Mostofthetime,itisbettertocatchexceptions,


eitherhandletheproblemordisplayanerrormessagetotheuserandthenquit.

18.8.Decorators
Decoratorsareashortcuttoapplyingwrapperfunctions.Thisishelpfulto"wrap"functionalitywiththe
samecodeoverandoveragain.Forexample,Icreateda retry decoratorformyselfthatIcanjust
applytoanyfunctionandifanyexceptionisthrownduringarun,itisretriedagain,tillamaximumof5
timesandwithadelaybetweeneachretry.Thisisespeciallyusefulforsituationswhereyouaretryingto
makeanetworkcalltoaremotecomputer:

http://www.swaroopch.com/notes/python/

137/165

1/4/2015

AByteofPython

fromtimeimportsleep
fromfunctoolsimportwraps
importlogging
logging.basicConfig()
log=logging.getLogger("retry")

PYTHON

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:

http://www.swaroopch.com/notes/python/

138/165

1/4/2015

AByteofPython

$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/lcpdecor.html
http://toumorokoshi.github.io/dryprinciplesthroughpythondecorators.html

18.9.DifferencesbetweenPython2andPython3
See:
"Six"library (http://pythonhosted.org/six/)
PortingtoPython3ReduxbyArmin (http://lucumr.pocoo.org/2013/5/21/portingtopython3redux/)
Python3experiencebyPyDanny (http://pydanny.com/experienceswithdjangopython3.html)
OfficialDjangoGuidetoPortingtoPython3 (https://docs.djangoproject.com/en/dev/topics/python3/)
DiscussiononWhataretheadvantagestopython3.x?
(http://www.reddit.com/r/Python/comments/22ovb3/what_are_the_advantages_to_python_3x/)

18.10.Summary
WehavecoveredsomemorefeaturesofPythoninthischapterandyetwehaventcoveredallthe
featuresofPython.However,atthisstage,wehavecoveredmostofwhatyouareevergoingtousein
practice.Thisissufficientforyoutogetstartedwithwhateverprogramsyouaregoingtocreate.
Next,wewilldiscusshowtoexplorePythonfurther.
[[WhatNext]]

http://www.swaroopch.com/notes/python/

139/165

1/4/2015

AByteofPython

Ifyouhavereadthisbookthoroughlytillnowandpracticedwritingalotofprograms,thenyoumust
havebecomecomfortableandfamiliarwithPython.YouhaveprobablycreatedsomePythonprogramsto
tryoutstuffandtoexerciseyourPythonskillsaswell.Ifyouhavenotdoneitalready,youshould.The
questionnowis'WhatNext?'.
Iwouldsuggestthatyoutacklethisproblem:

Create your own commandline addressbookprogram using which you can


browse,add,modify,deleteorsearchfor yourcontactssuchasfriends,familyand
colleagues and their information such as email address and/or phone number.
Detailsmustbestoredforlaterretrieval.

Thisisfairlyeasyifyouthinkaboutitintermsofallthevariousstuffthatwehavecomeacrosstillnow.
Ifyoustillwantdirectionsonhowtoproceed,thenheresahint[3].
Onceyouareabletodothis,youcanclaimtobeaPythonprogrammer.Now,immediatelysendmean
email (http://swaroopch.com/contact/)thankingmeforthisgreatbook).Thisstepisoptionalbut
recommended.Also,pleaseconsiderbuyingaprintedcopy (http://swaroopch.com/buybook/)tosupportthe
continueddevelopmentofthisbook.
Ifyoufoundthatprogrameasy,heresanotherone:

Implement the replace command (http://unixhelp.ed.ac.uk/CGI/mancgi?replace). This


commandwillreplaceonestringwithanotherinthelistoffilesprovided.

Thereplacecommandcanbeassimpleorassophisticatedasyouwish,fromsimplestringsubstitutionto
lookingforpatterns(regularexpressions).

18.11.NextProjects
Ifyoufoundaboveprogramseasytocreate,thenlookatthiscomprehensivelistofprojectsandtry
writingyourownprograms:https://github.com/thekarangoel/Projects#numbers(thelistisalsoat
Martyr2sMegaProjectList (http://www.dreamincode.net/forums/topic/78802martyr2smegaprojectideaslist/)).
AlsoseeIntermediatePythonProjects (https://openhatch.org/wiki/Intermediate_Python_Workshop/Projects).

18.12.ExampleCode
Thebestwaytolearnaprogramminglanguageistowritealotofcodeandreadalotofcode:
http://www.swaroopch.com/notes/python/

140/165

1/4/2015

AByteofPython

PythonCookbook (http://code.activestate.com/recipes/langs/python/)isanextremelyvaluablecollectionof
recipesortipsonhowtosolvecertainkindsofproblemsusingPython.Thisisamustreadforevery
Pythonuser.
PythonModuleoftheWeek (http://pymotw.com/2/contents.html)isanotherexcellentmustreadguideto
theStandardLibrary.

18.13.Advice
TheHitchhikersGuidetoPython! (http://docs.pythonguide.org/en/latest/)
PythonBigPicture (http://slottsoftwarearchitect.blogspot.ca/2013/06/pythonbigpicturewhatsroadmap.html)
"WritingIdiomaticPython"ebook (http://www.jeffknupp.com/writingidiomaticpythonebook/)(paid)

18.14.Videos
PyVideo (http://www.pyvideo.org)

18.15.QuestionsandAnswers
OfficialPythonDosandDonts (http://docs.python.org/3/howto/doanddont.html)
OfficialPythonFAQ (http://www.python.org/doc/faq/general/)
NorvigslistofInfrequentlyAskedQuestions (http://norvig.com/pythoniaq.html)
PythonInterviewQ&A (http://dev.fyicenter.com/InterviewQuestions/Python/index.html)
StackOverflowquestionstaggedwithpython (http://stackoverflow.com/questions/tagged/python)

18.16.Tutorials
HiddenfeaturesofPython (http://stackoverflow.com/q/101268/4869)
Whatstheonecodesnippet/pythontrick/etcdidyouwishyouknewwhenyoulearnedpython?
(http://www.reddit.com/r/Python/comments/19dir2/whats_the_one_code_snippetpython_tricketc_did_you/)

AwaretekscomprehensivelistofPythontutorials (http://www.awaretek.com/tutorials.html)

18.17.Discussion
IfyouarestuckwithaPythonproblem,anddontknowwhomtoask,thenthepythontutorlist
(http://mail.python.org/mailman/listinfo/tutor)isthebestplacetoaskyourquestion.

Makesureyoudoyourhomeworkbytryingtosolvingtheproblemyourselffirstandasksmartquestions
(http://catb.org/~esr/faqs/smartquestions.html).
http://www.swaroopch.com/notes/python/

141/165

1/4/2015

AByteofPython

18.18.News
IfyouwanttolearnwhatisthelatestintheworldofPython,thenfollowtheOfficialPythonPlanet
(http://planet.python.org).

18.19.Installinglibraries
ThereareahugenumberofopensourcelibrariesatthePythonPackageIndex (http://pypi.python.org/pypi)
whichyoucanuseinyourownprograms.
Toinstallandusetheselibraries,youcanusepip (http://www.pipinstaller.org/en/latest/).

18.20.CreatingaWebsite
LearnFlask (http://flask.pocoo.org)tocreateyourownwebsite.Someresourcestogetstarted:
FlaskOfficialQuickstart (http://flask.pocoo.org/docs/quickstart/)
TheFlaskMegaTutorial (http://blog.miguelgrinberg.com/post/theflaskmegatutorialpartihelloworld)
ExampleFlaskProjects (https://github.com/mitsuhiko/flask/tree/master/examples)

18.21.GraphicalSoftware
SupposeyouwanttocreateyourowngraphicalprogramsusingPython.ThiscanbedoneusingaGUI
(GraphicalUserInterface)librarywiththeirPythonbindings.Bindingsarewhatallowyoutowrite
programsinPythonandusethelibrarieswhicharethemselveswritteninCorC++orotherlanguages.
TherearelotsofchoicesforGUIusingPython:
Kivy
http://kivy.org
PyGTK
ThisisthePythonbindingfortheGTK+toolkitwhichisthefoundationuponwhichGNOMEisbuilt.
GTK+hasmanyquirksinusagebutonceyoubecomecomfortable,youcancreateGUIappsfast.The
Gladegraphicalinterfacedesignerisindispensable.Thedocumentationisyettoimprove.GTK+
workswellonGNU/LinuxbutitsporttoWindowsisincomplete.Youcancreatebothfreeaswellas
proprietarysoftwareusingGTK+.Togetstarted,readthePyGTKtutorial
(http://www.pygtk.org/tutorial.html).

PyQt

http://www.swaroopch.com/notes/python/

142/165

1/4/2015

AByteofPython

ThisisthePythonbindingfortheQttoolkitwhichisthefoundationuponwhichtheKDEisbuilt.Qt
isextremelyeasytouseandverypowerfulespeciallyduetotheQtDesignerandtheamazingQt
documentation.PyQtisfreeifyouwanttocreateopensource(GPLed)softwareandyouneedtobuy
itifyouwanttocreateproprietaryclosedsourcesoftware.StartingwithQt4.5youcanuseittocreate
nonGPLsoftwareaswell.Togetstarted,readaboutPySide (http://qtproject.org/wiki/PySide).
wxPython
ThisisthePythonbindingsforthewxWidgetstoolkit.wxPythonhasalearningcurveassociatedwith
it.However,itisveryportableandrunsonGNU/Linux,Windows,Macandevenembedded
platforms.TherearemanyIDEsavailableforwxPythonwhichincludeGUIdesignersaswellsuchas
SPE(StanisPythonEditor) (http://spe.pycs.net/)andthewxGlade (http://wxglade.sourceforge.net/)GUI
builder.YoucancreatefreeaswellasproprietarysoftwareusingwxPython.Togetstarted,readthe
wxPythontutorial (http://zetcode.com/wxpython/).

18.22.SummaryofGUITools
Formorechoices,seetheGuiProgrammingwikipageattheofficialpythonwebsite
(http://www.python.org/cgibin/moinmoin/GuiProgramming).

Unfortunately,thereisnoonestandardGUItoolforPython.Isuggestthatyouchooseoneoftheabove
toolsdependingonyoursituation.ThefirstfactoriswhetheryouarewillingtopaytouseanyoftheGUI
tools.ThesecondfactoriswhetheryouwanttheprogramtorunonlyonWindowsoronMacand
GNU/Linuxorallofthem.Thethirdfactor,ifGNU/Linuxisachosenplatform,iswhetheryouarea
KDEorGNOMEuseronGNU/Linux.
Foramoredetailedandcomprehensiveanalysis,seePage26ofthe'ThePythonPapers,Volume3,Issue
1' (http://archive.pythonpapers.org/ThePythonPapersVolume3Issue1.pdf).

18.23.VariousImplementations
Thereareusuallytwopartsaprogramminglanguagethelanguageandthesoftware.Alanguageishow
youwritesomething.Thesoftwareiswhatactuallyrunsourprograms.
WehavebeenusingtheCPythonsoftwaretorunourprograms.ItisreferredtoasCPythonbecauseitis
writtenintheClanguageandistheClassicalPythoninterpreter.
TherearealsoothersoftwarethatcanrunyourPythonprograms:
Jython (http://www.jython.org)

http://www.swaroopch.com/notes/python/

143/165

1/4/2015

AByteofPython

APythonimplementationthatrunsontheJavaplatform.ThismeansyoucanuseJavalibrariesand
classesfromwithinPythonlanguageandviceversa.
IronPython (http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPython)
APythonimplementationthatrunsonthe.NETplatform.Thismeansyoucanuse.NETlibrariesand
classesfromwithinPythonlanguageandviceversa.
PyPy (http://codespeak.net/pypy/dist/pypy/doc/home.html)
APythonimplementationwritteninPython!Thisisaresearchprojecttomakeitfastandeasyto
improvetheinterpretersincetheinterpreteritselfiswritteninadynamiclanguage(asopposedto
staticlanguagessuchasC,JavaorC#intheabovethreeimplementations)
TherearealsootherssuchasCLPython (http://commonlisp.net/project/clpython/)aPythonimplementation
writteninCommonLispandBrython (http://brython.info/)whichisanimplementationontopofa
JavaScriptinterpreterwhichcouldmeanthatyoucanusePython(insteadofJavaScript)towriteyour
webbrowser("Ajax")programs.
Eachoftheseimplementationshavetheirspecializedareaswheretheyareuseful.

18.24.FunctionalProgramming(foradvancedreaders)
Whenyoustartwritinglargerprograms,youshoulddefinitelylearnmoreaboutafunctionalapproachto
programmingasopposedtotheclassbasedapproachtoprogrammingthatwelearnedintheobject
orientedprogrammingchapter:
FunctionalProgrammingHowtobyA.M.Kuchling (http://docs.python.org/3/howto/functional.html)
Functionalprogrammingchapterin'DiveIntoPython'book
(http://www.diveintopython.net/functional_programming/index.html)

FunctionalProgrammingwithPythonpresentation (http://ua.pycon.org/static/talks/kachayev/index.html)
Funcylibrary (https://github.com/Suor/funcy)

18.25.Summary
Wehavenowcometotheendofthisbookbut,astheysay,thisisthethebeginningoftheend!.Youare
nowanavidPythonuserandyouarenodoubtreadytosolvemanyproblemsusingPython.Youcanstart
automatingyourcomputertodoallkindsofpreviouslyunimaginablethingsorwriteyourowngames
andmuchmuchmore.So,getstarted!

http://www.swaroopch.com/notes/python/

144/165

1/4/2015

AByteofPython

19.Appendix:FLOSS
NOTE

Pleasenotethatthissectionwaswrittenin2003,sosomeofthismightsoundquaintto
you:)

"Free/LibreandOpenSourceSoftware",inshort,FLOSS (http://en.wikipedia.org/wiki/FLOSS)isbasedon
theconceptofacommunity,whichitselfisbasedontheconceptofsharing,andparticularlythesharing
ofknowledge.FLOSSarefreeforusage,modificationandredistribution.
Ifyouhavealreadyreadthisbook,thenyouarealreadyfamiliarwithFLOSSsinceyouhavebeenusing
PythonallalongandPythonisanopensourcesoftware!
HerearesomeexamplesofFLOSStogiveanideaofthekindofthingsthatcommunitysharingand
buildingcancreate:
Linux (http://www.kernel.org)
ThisisaFLOSSOSkernelusedintheGNU/Linuxoperatingsystem.Linux,thekernel,wasstarted
byLinusTorvaldsasastudent.AndroidisbasedonLinux.Anywebsiteyouusethesedayswill
mostlyberunningonLinux.
Ubuntu (http://www.ubuntu.com)
Thisisacommunitydrivendistribution,sponsoredbyCanonicalanditisthemostpopular
GNU/Linuxdistributiontoday.ItallowsyoutoinstallaplethoraofFLOSSavailableandallthisinan
easytouseandeasytoinstallmanner.Bestofall,youcanjustrebootyourcomputerandrun
GNU/LinuxofftheCD!ThisallowsyoutocompletelytryoutthenewOSbeforeinstallingitonyour
computer.However,Ubuntuisnotentirelyfreesoftwareitcontainsproprietarydrivers,firmware,and
applications.
LibreOffice (http://www.libreoffice.org/)
Thisisanexcellentcommunitydrivenanddevelopedofficesuitewithawriter,presentation,
spreadsheetanddrawingcomponentsamongotherthings.ItcanevenopenandeditMSWordandMS
PowerPointfileswithease.Itrunsonalmostallplatformsandisentirelyfree,libreandopensource
software.
MozillaFirefox (http://www.mozilla.org/products/firefox)
Thisisthebestwebbrowser.Itisblazinglyfastandhasgainedcriticalacclaimforitssensibleand
impressivefeatures.Theextensionsconceptallowsanykindofpluginstobeused.

http://www.swaroopch.com/notes/python/

145/165

1/4/2015

AByteofPython

Mono (http://www.monoproject.com)
ThisisanopensourceimplementationoftheMicrosoft.NETplatform.Itallows.NETapplicationsto
becreatedandrunonGNU/Linux,Windows,FreeBSD,MacOSandmanyotherplatformsaswell.
Apachewebserver (http://httpd.apache.org)
Thisisthepopularopensourcewebserver.Infact,itisthemostpopularwebserverontheplanet!It
runsnearlymorethanhalfofthewebsitesoutthere.Yes,thatsrightApachehandlesmorewebsites
thanallthecompetition(includingMicrosoftIIS)combined.
VLCPlayer (http://www.videolan.org/vlc/)
ThisisavideoplayerthatcanplayanythingfromDivXtoMP3toOggtoVCDsandDVDstowho
saysopensourceaintfun?)
ThislistisjustintendedtogiveyouabriefideatherearemanymoreexcellentFLOSSoutthere,such
asthePerllanguage,PHPlanguage,Drupalcontentmanagementsystemforwebsites,PostgreSQL
databaseserver,TORCSracinggame,KDevelopIDE,Xinethemovieplayer,VIMeditor,Quanta+
editor,Bansheeaudioplayer,GIMPimageeditingprogram,Thislistcouldgoonforever.
TogetthelatestbuzzintheFLOSSworld,checkoutthefollowingwebsites:
OMG!Ubuntu! (http://www.omgubuntu.co.uk/)
WebUpd8 (http://www.webupd8.org/)
DistroWatch (http://www.distrowatch.com)
PlanetDebian (http://planet.debian.org/)
VisitthefollowingwebsitesformoreinformationonFLOSS:
GitHubExplore (http://github.com/explore)
CodeTriage (http://www.codetriage.com/)
SourceForge (http://www.sourceforge.net)
FreshMeat (http://www.freshmeat.net)
So,goaheadandexplorethevast,freeandopenworldofFLOSS!

http://www.swaroopch.com/notes/python/

146/165

1/4/2015

AByteofPython

20.Appendix:Colophon
AlmostallofthesoftwarethatIhaveusedinthecreationofthisbookareFLOSS.

20.1.BirthoftheBook
Inthefirstdraftofthisbook,IhadusedRedHat9.0Linuxasthefoundationofmysetupandinthesixth
draft,IusedFedoraCore3Linuxasthebasisofmysetup.
Initially,IwasusingKWordtowritethebook(asexplainedinthehistorylessoninthepreface).

20.2.TeenageYears
Later,IswitchedtoDocBookXMLusingKatebutIfoundittootedious.So,IswitchedtoOpenOffice
whichwasjustexcellentwiththelevelofcontrolitprovidedforformattingaswellasthePDF
generation,butitproducedverysloppyHTMLfromthedocument.
Finally,IdiscoveredXEmacsandIrewrotethebookfromscratchinDocBookXML(again)afterI
decidedthatthisformatwasthelongtermsolution.
Inthesixthdraft,IdecidedtouseQuanta+todoalltheediting.ThestandardXSLstylesheetsthatcame
withFedoraCore3Linuxwerebeingused.However,IhadwrittenaCSSdocumenttogivecolorand
styletotheHTMLpages.Ihadalsowrittenacrudelexicalanalyzer,inPythonofcourse,which
automaticallyprovidessyntaxhighlightingtoalltheprogramlistings.
Fortheseventhdraft,ImusingMediaWiki (http://www.mediawiki.org)asthebasisofmysetup.Iusedto
editeverythingonlineandthereaderscandirectlyread/edit/discusswithinthewikiwebsite,butIended
upspendingmoretimefightingspamthanwriting.
Fortheeightdraft,IusedVim (http://www.swaroopch.com/notes/vim),Pandoc
(http://johnmacfarlane.net/pandoc/README.html),andMacOSX.

20.3.Now
Fortheninthdraft,IswitchedtoAsciiDocformat (http://asciidoctor.org/docs/whatisasciidoc/)andused
Emacs24.3 (http://www.masteringemacs.org/articles/2013/03/11/whatsnewemacs243/),tomorrowtheme
(https://github.com/chriskempson/tomorrowtheme),FiraMonofont
(https://www.mozilla.org/enUS/styleguide/products/firefoxos/typeface/#downloadprimary)andadocmode
(https://github.com/sensorflo/adocmode/wiki)towrite.

20.4.AbouttheAuthor
http://www.swaroopch.com/notes/python/

147/165

1/4/2015

AByteofPython

Seehttp://swaroopch.com/about/

http://www.swaroopch.com/notes/python/

148/165

1/4/2015

AByteofPython

21.Appendix:HistoryLesson
IfirststartedwithPythonwhenIneededtowriteaninstallerforsoftwareIhadwrittencalled'Diamond'
sothatIcouldmaketheinstallationeasy.IhadtochoosebetweenPythonandPerlbindingsfortheQt
library.IdidsomeresearchonthewebandIcameacrossanarticlebyEricS.Raymond
(http://www.python.org/about/success/esr/),afamousandrespectedhacker,wherehetalkedabouthow

Pythonhadbecomehisfavoriteprogramminglanguage.IalsofoundoutthatthePyQtbindingswere
morematurecomparedtoPerlQt.So,IdecidedthatPythonwasthelanguageforme.
Then,IstartedsearchingforagoodbookonPython.Icouldntfindany!IdidfindsomeOReillybooks
buttheywereeithertooexpensiveorweremorelikeareferencemanualthanaguide.So,Isettledforthe
documentationthatcamewithPython.However,itwastoobriefandsmall.Itdidgiveagoodideaabout
Pythonbutwasnotcomplete.ImanagedwithitsinceIhadpreviousprogrammingexperience,butitwas
unsuitablefornewbies.
AboutsixmonthsaftermyfirstbrushwithPython,Iinstalledthe(then)latestRedHat9.0LinuxandI
wasplayingaroundwithKWord.Igotexcitedaboutitandsuddenlygottheideaofwritingsomestuffon
Python.Istartedwritingafewpagesbutitquicklybecame30pageslong.Then,Ibecameseriousabout
makingitmoreusefulinabookform.Afteralotofrewrites,ithasreachedastagewhereithasbecomea
usefulguidetolearningthePythonlanguage.Iconsiderthisbooktobemycontributionandtributetothe
opensourcecommunity.
ThisbookstartedoutasmypersonalnotesonPythonandIstillconsideritinthesameway,although
Ivetakenalotofefforttomakeitmorepalatabletoothers:)
Inthetruespiritofopensource,Ihavereceivedlotsofconstructivesuggestions,criticismsandfeedback
fromenthusiasticreaderswhichhashelpedmeimprovethisbookalot.

21.1.StatusOfTheBook
Thebookwaslastupdatedon20141204andgeneratedusingAsciiDoctor (http://www.asciidoctor.org)
1.5.1.
LastmajorupdateofthisbookwasinMarApr2014,convertedtoAsciidoc
(http://asciidoctor.org/docs/whatisasciidoc/)usingEmacs24
(http://swaroopch.com/2013/10/17/emacsconfigurationtutorial/)andadocmode
(https://github.com/sensorflo/adocmode/wiki).

InDec2008,thebookwasupdatedforthePython3.0release(oneofthefirstbookstodoso).But
now,IhaveconvertedthebookbackforPython2languagebecausereaderswouldoftengetconfused
betweenthedefaultPython2installedontheirsystemsvs.Python3whichtheyhadtoseparately
http://www.swaroopch.com/notes/python/

149/165

1/4/2015

AByteofPython

installandallthetooling,esp.editorswouldassumePython2aswell.Ihadahardtimejustifying
whyIhadtoaggravatereadersandmakethemgothroughallthiswhenthefactisthattheycanlearn
eitheroneanditwouldbejustasuseful.So,Python2itis.
Thebookneedsthehelpofitsreaderssuchasyourselvestopointoutanypartsofthebookwhicharenot
good,notcomprehensibleoraresimplywrong.Pleasewritetothemainauthor
(http://swaroopch.com/contact)ortherespectivetranslatorswithyourcommentsandsuggestions.

http://www.swaroopch.com/notes/python/

150/165

1/4/2015

AByteofPython

22.Appendix:RevisionHistory
3.0
31Mar2014
RewrittenusingAsciiDoc (http://asciidoctor.org/docs/whatisasciidoc/)andadocmode
(https://github.com/sensorflo/adocmode/wiki).

2.1
03Aug2013
RewrittenusingMarkdownandJasonBlevins'MarkdownMode
(http://jblevins.org/projects/markdownmode/)

2.0
20Oct2012
RewritteninPandocformat (http://johnmacfarlane.net/pandoc/README.html),thankstomywifewho
didmostoftheconversionfromtheMediawikiformat
Simplifyingtext,removingnonessentialsectionssuchas nonlocal andmetaclasses
1.90
04Sep2008andstillinprogress
Revivalafteragapof3.5years!
RewritingforPython3.0
RewriteusingMediaWiki (http://www.mediawiki.org)(again)
1.20
13Jan2005
CompleterewriteusingQuanta+ (https://en.wikipedia.org/wiki/Quanta_Plus)onFedora
(http://fedoraproject.org/)Core3withlotofcorrectionsandupdates.Manynewexamples.Rewrote

myDocBooksetupfromscratch.
1.15
28Mar2004
Minorrevisions
1.12

http://www.swaroopch.com/notes/python/

151/165

1/4/2015

AByteofPython

16Mar2004
Additionsandcorrections
1.10
09Mar2004
Moretypocorrections,thankstomanyenthusiasticandhelpfulreaders.
1.00
08Mar2004
Aftertremendousfeedbackandsuggestionsfromreaders,Ihavemadesignificantrevisionstothe
contentalongwithtypocorrections.
0.99
22Feb2004
Addedanewchapteronmodules.Addeddetailsaboutvariablenumberofargumentsinfunctions.
0.98
16Feb2004
WroteaPythonscriptandCSSstylesheettoimproveXHTMLoutput,includingacrudeyet
functionallexicalanalyzerforautomaticVIMlikesyntaxhighlightingoftheprogramlistings.
0.97
13Feb2004
Anothercompletelyrewrittendraft,inDocBookXML(again).Bookhasimprovedalotitis
morecoherentandreadable.
0.93
25Jan2004
AddedIDLEtalkandmoreWindowsspecificstuff
0.92
05Jan2004
Changestofewexamples.
0.91
30Dec2003

http://www.swaroopch.com/notes/python/

152/165

1/4/2015

AByteofPython

Correctedtypos.Improvisedmanytopics.
0.90
18Dec2003
Added2morechapters.OpenOffice (https://en.wikipedia.org/wiki/OpenOffice)formatwithrevisions.
0.60
21Nov2003
Fullyrewrittenandexpanded.
0.20
20Nov2003
Correctedsometyposanderrors.
0.15
20Nov2003
ConvertedtoDocBookXML (https://en.wikipedia.org/wiki/DocBook)withXEmacs.
0.10
14Nov2003
InitialdraftusingKWord (https://en.wikipedia.org/wiki/Kword).

http://www.swaroopch.com/notes/python/

153/165

1/4/2015

AByteofPython

23.Translations
Therearemanytranslationsofthebookavailableindifferenthumanlanguages,thankstomanytireless
volunteers!
Ifyouwanttohelpwiththesetranslations,pleaseseethelistofvolunteersandlanguagesbelowand
decideifyouwanttostartanewtranslationorhelpinexistingtranslationprojects.
Ifyouplantostartanewtranslation,pleasereadtheTranslationHowto.

23.1.Arabic
BelowisthelinkfortheArabicversion.ThankstoAshrafAliKhalaffortranslatingthebook,youcan
readthewholebookonlineathttp://www.khaledhosny.org/byteofpython/index.htmloryoucan
downloaditfromsourceforge.net
(http://downloads.sourceforge.net/omlx/byteofpython_arabic.pdf?use_mirror=osdn)formoreinfosee

http://itwadi.com/byteofpython_arabi.

23.2.BrazilianPortuguese
Therearetwotranslations:
SamuelDiasNeto (http://www.samueldiasneto.com/aprendendopython/index.html)(samuel.arataca@gmail.com)
madethefirstBrazilianPortuguesetranslationofthisbookwhenPythonwasin2.3.5version.
Samuelstranslationisavailableataprendendopython
(http://www.samueldiasneto.com/aprendendopython/index.html).

RodrigoAmaral (http://rodrigoamaral.net)(rodrigoamaral@gmail.com)hasvolunteeredtotranslatethebook
toBrazilianPortuguese.

23.3.Catalan
MoisesGomez(moisesgomezgiron@gmail.com)hasvolunteeredtotranslatethebooktoCatalan.The
translationisinprogress.

http://www.swaroopch.com/notes/python/

154/165

1/4/2015

AByteofPython

Moiss Gmez I am a developer and also a teacher of programming (normally


forpeoplewithoutanypreviousexperience).
Some time ago I needed to learn how to program in Python, and Swaroops work
wasreallyhelpful.Clear,concise,andcompleteenough.JustwhatIneeded.
After this experience, I thought some other people in my country could take
benefitfromittoo.ButEnglishlanguagecanbeabarrier.
So,whynottrytotranslateit?AndIdidforapreviousversionofBoP.
I my country there are two official languages. I selected the Catalan language
assumingthatotherswilltranslateittothemorewidespreadSpanish.

23.4.Chinese
Translationsareavailableathttp://woodpecker.org.cn/abyteofpython_cn/chinese/and
http://zhgdg.gitcafe.com/static/doc/byte_of_python.html.
JuanShen(orion_val@163.com)hasvolunteeredtotranslatethebooktoChinese.

I am a postgraduate at Wireless Telecommunication Graduate School, Beijing


University of Technology, China PR. My current research interest is on the
synchronization, channel estimation and multiuser detection of multicarrier
CDMA system. Python is my major programming language for daily simulation
andresearch job,with thehelp ofPython Numeric,actually. Ilearned Pythonjust
half a year before, but as you can see, its really easyunderstanding, easytouse
and productive. Just as what is ensured in Swaroops book, 'Its my favorite
programminglanguagenow'.
'A Byte of Python' is my tutorial to learn Python. Its clear and effective to lead
you into a world of Python in the shortest time. Its not too long, but efficiently
covers almost allimportant things in Python.I think 'A Byte ofPython' should be
strongly recommendable for newbies as their first Python tutorial. Just dedicate
mytranslationtothepotentialmillionsofPythonusersinChina.

http://www.swaroopch.com/notes/python/

155/165

1/4/2015

AByteofPython

23.5.ChineseTraditional
FredLin(gasolin@gmail.com)hasvolunteeredtotranslatethebooktoChineseTraditional.
Itisavailableathttp://code.google.com/p/zhpy/wiki/ByteOfZhpy.
Anexcitingfeatureofthistranslationisthatitalsocontainstheexecutablechinesepythonsourcesside
bysidewiththeoriginalpythonsources.

FredLinImworkingasa networkfirmwareengineeratDeltaNetwork,andIm
alsoacontributorofTurboGearswebframework.
As a python evangelist (:p), I need some material to promote python language. I
found 'A Byte of Python' hit the sweet point for both newbies and experienced
programmers. 'A Byte of Python' elaborates the python essentials with affordable
size.
The translation are originally based on simplified chinese version, and soon a lot
ofrewriteweremadetofitthecurrentwikiversionandthequalityofreading.
The recent chinese traditional version also featured with executable chinese
python sources, which are achieved by my new 'zhpy' (python in chinese) project
(launchfromAug07).
zhpy(pronounce (Z.H.?, or zippy) build a layer upon python to translate or
interact with python in chinese(Traditional or Simplified). This project is mainly
aimedforeducation.

23.6.French
Gregory(coulix@ozforces.com.au)hasvolunteeredtotranslatethebooktoFrench.
GrardLabadie(gerard.labadie@gmail.com)hascompletedtotranslatethebooktoFrench.

23.7.German
LutzHorn(lutz.horn@gmx.de),BerndHengelein(bernd.hengelein@gmail.com)andChristoph
Zwerschke(cito@online.de)havevolunteeredtotranslatethebooktoGerman.
http://www.swaroopch.com/notes/python/

156/165

1/4/2015

AByteofPython

Theirtranslationislocatedathttp://ftp.jaist.ac.jp/pub//sourceforge/a/ab/abopgerman.berlios/
LutzHornsays:

Im 32 years old and have a degree of Mathematics from University of


Heidelberg,Germany. CurrentlyIm workingas asoftware engineeron apublicly
funded project to build a web portal for all things related to computer science in
Germany.The main language I use as a professional is Java, but I try to do as
much as possible with Python behind the scenes. Especially text analysis and
conversionisvery easywithPython.Im notveryfamiliarwith GUItoolkits,since
most of my programming is about web applications, where the user interface is
build using Java frameworks like Struts. Currently I try to make more use of the
functionalprogramming featuresof Pythonandof generators.Aftertaking ashort
look into Ruby, I was very impressed with the use of blocks in this language.
Generally I like the dynamic nature of languages like Python and Ruby since it
allows me to do things not possible in more static languages like Java.Ive
searched for some kind of introduction to programming, suitable to teach a
complete nonprogrammer. Ive found the book 'How to Think Like a Computer
Scientist: Learning with Python', and 'Dive into Python'. The first is good for
beginnersbuttolong totranslate.Thesecondisnotsuitable forbeginners.Ithink
'AByteof Python'fallsnicelybetweenthese, sinceitisnottoolong, writtentothe
point, andat the sametime verbose enoughto teach anewbie. Besides this,I like
the simple DocBook structure, which makes translating the text a generation the
outputinvariousformatsacharm.

BerndHengeleinsays:

http://www.swaroopch.com/notes/python/

157/165

1/4/2015

AByteofPython

Lutz andme are going todo the germantranslation together. We juststarted with
the intro and preface but we will keep you informed about the progress we make.
Ok, now some personal things about me. I am 34 years old and playing with
computerssincethe 1980s,whenthe"CommodoreC64"ruled thenurseries.After
studying computer science I started working as a software engineer. Currently I
am working in the field of medical imaging for a major german company.
Although C++ is the main language I (have to) use for my daily work, I am
constantly looking for new things to learn.Last year I fell in love with Python,
which is a wonderful language, both for its possibilities and its beauty. I read
somewherein thenet aboutaguy whosaid thathelikes python,because thecode
looks so beautiful. In my opinion hes absolutly right. At the time I decided to
learn python, I noticed that there is very little good documentation in german
available. When I came across your book the spontaneous idea of a german
translation crossed my mind. Luckily, Lutz had the same idea and we can now
dividethework.Iamlookingforwardtoagoodcooperation!

23.8.Greek
TheGreekUbuntuCommunitytranslatedthebookinGreek (http://wiki.ubuntugr.org/byteofpythonel),for
useinouronlineasynchronousPythonlessonsthattakeplaceinourforums.Contact@savvasradevic
(https://twitter.com/savvasradevic)formoreinformation.

23.9.Indonesian
Daniel(daniel.mirror@gmail.com)istranslatingthebooktoIndonesianat
http://python.or.id/moin.cgi/ByteofPython.
WisnuPriyambodo(cibermen@gmail.com)alsohasvolunteeredtotranslatethebooktoIndonesian.
Also,BagusAjiSantoso(baguzzzaji@gmail.com)hasvolunteered.

23.10.Italian
EnricoMorelli(mr.mlucci@gmail.com)andMassimoLucci(morelli@cerm.unifi.it)havevolunteeredto
translatethebooktoItalian.
TheItaliantranslationispresentathttp://www.gentoo.it/Programmazione/byteofpython.
http://www.swaroopch.com/notes/python/

158/165

1/4/2015

AByteofPython

MassimoLucci andEnricoMorelli weare workingat theUniversity ofFlorence


(Italy) Chemistry Department. I (Massimo) as service engineer and system
administrator for Nuclear Magnetic Resonance Spectrometers Enrico as service
engineer and system administrator for our CED and parallel / clustered systems.
We are programming on python since about seven years, we had experience
working with Linux platforms since ten years. In Italy we are responsible and
administrator for www.gentoo.it web site for Gentoo/Linux distrubution and
www.nmr.it (now under construction) for Nuclear Magnetic Resonance
applications and Congress Organization and Managements.Thats all! We are
impressed bythe smartlanguage usedon yourBook andwe thinkthis isessential
for approaching the Python to new users (we are thinking about hundred of
studentsandresearcherworkingonourlabs).

23.11.Japanese
ShunroDozono(dozono@gmail.com)istranslatingthebooktoJapanese.

23.12.Korean
JeongbinPark(pjb7687@gmail.com)hastranslatedthebooktoKorean
https://github.com/pjb7687/byte_of_python

http://www.swaroopch.com/notes/python/

159/165

1/4/2015

AByteofPython

I am Jeongbin Park, currently working as a Biophysics & Bioinformatics


researcherinKorea.
A year ago, I was looking for a good tutorial/guide for Python to introduce it to
my colleagues, because using Python in such research fields is becoming
inevitableduetotheuserbaseisgrowingmoreandmore.
But at that time only few Python books are available in Korean, so I decided to
translate your ebook because it looks like one of the best guides that I have ever
read!
Currently, the book is almost completely translated in Korean, except some of the
textinintroductionchapterandtheappendixes.
Thankyouagainforwritingsuchagoodguide!

23.13.Mongolian
AriunsanaaTunjin(luftballons2010@gmail.com)hasvolunteeredtotranslatethebooktoMongolian.
UpdateonNov22,2009:Ariunsanaaisonthevergeofcompletingthetranslation.

23.14.Norwegian(bokml)
EirikVgeskarisahighschoolstudentatSandvikavideregendeskole
(http://no.wikipedia.org/wiki/Sandvika_videreg%C3%A5ende_skole)inNorway,ablogger
(http://forbedre.blogspot.com/)andcurrentlytranslatingthebooktoNorwegian(bokml).

http://www.swaroopch.com/notes/python/

160/165

1/4/2015

AByteofPython

Eirik Vgeskar: I have always wanted to program, but because I speak a small
language, the learning process was much harder. Most tutorials and books are
written in very technical English, so most high school graduates will not even
have the vocabulary to understand what the tutorial is about. When I discovered
this book, all my problems were solved. "A Byte of Python" used simple non
technical languageto explain aprogramming language thatis just assimple, and
these two things make learning Python fun. After reading half of the book, I
decided that the book was worth translating. I hope the translation will help
people who have found themself in the same situation as me (especially young
people), and maybe help spread interest for the language among people with less
technicalknowledge.

23.15.Polish
DominikKozaczko(dominik@kozaczko.info)hasvolunteeredtotranslatethebooktoPolish.
Translationisinprogressanditsmainpageisavailablehere:UkPythona
(http://python.edu.pl/byteofpython/).

Update:ThetranslationiscompleteandreadyasofOct2,2009.ThankstoDominik,histwostudents
andtheirfriendfortheirtimeandeffort!

DominikKozaczkoImaComputerScienceandInformationTechnologyteacher.

23.16.Portuguese
FidelViegas(fidel.viegas@gmail.com)hasvolunteeredtotranslatethebooktoPortuguese.

23.17.Romanian
PaulSebastianManole(brokenthorn@gmail.com)hasvolunteeredtotranslatethisbooktoRomanian.

http://www.swaroopch.com/notes/python/

161/165

1/4/2015

AByteofPython

PaulSebastian Manole Im a second year Computer Science student at Spiru


Haret University, here in Romania. Im more of a selftaught programmer and
decided to learn a new language, Python. The web told me there was no better
way to do so but read ''A Byte of Python''. Thats how popular this book is
(congratulations to the author for writing such an easy to read book). I started
likingPythonsoI decidedtohelptranslatethelatestversion ofSwaroopsbookin
Romanian. Although I could be the one with the first initiative, Im just one
volunteersoifyoucanhelp,pleasejoinme.

23.18.Russian
VladimirSmolyar(v_2e@ukr.net)hascompletedaRussiantranslationat
http://wombat.org.ua/AByteOfPython/.

23.19.Ukranian
AverkievAndrey(averkiyev@ukr.net)hasvolunteeredtotranslatethebooktoRussian,andperhaps
Ukranian(timepermitting).

23.20.Serbian
"BugSpice"(amortizerka@gmail.com)hascompletedaSerbiantranslation:

You

can

download

it

http://www.sendspace.com/filegroup/DlNY1mF7DFqNt4e61LvVug (Latin

from
and

Cyrillicserbian(andsimilarlanguages)version.
Moredetailsathttp://forum.ubunturs.org/Threadzagrljajpitona.

23.21.Slovak
AlbertioWard(albertioward@gmail.com)hastranslatedthebooktoSlovakat
http://www.fatcow.com/edu/pythonswaroopchsl/:

http://www.swaroopch.com/notes/python/

162/165

1/4/2015

AByteofPython

We are a nonprofit organization called "Translation for education". We represent


a group of people, mainly students and professors, of the Slavonic University.
Here are students from different departments: linguistics, chemistry, biology, etc.
We try to find interesting publications on the Internet that can be relevant for us
and our university colleagues. Sometimes we find articles by ourselves other
times our professors help us choose the material for translation. After obtaining
permission from authors we translate articles and post them in our blog which is
available and accessible to our colleagues and friends. These translated
publicationsoftenhelpstudentsintheirdailystudyroutine.

23.22.Spanish
AlfonsodelaGuardaReyes(alfonsodg@ictechperu.net),GustavoEcheverria
(gustavo.echeverria@gmail.com),DavidCrespoArroyo(davidcrespoarroyo@hotmail.com)andCristian
BermudezSerna(crisbermud@hotmail.com)havevolunteeredtotranslatethebooktoSpanish.
GustavoEcheverriasays:

Iwork asa softwareengineer inArgentina.I usemostly C#and .Nettechnologies


at work but strictlyPython or Ruby in my personal projects.I knew Python many
years ago and I got stuck inmediately. Not so long after knowing Python I
discoveredthisbookandithelpedme tolearnthelanguage.ThenIvolunteeredto
translate the book to Spanish. Now, after receiving some requests, Ive begun to
translate"AByteofPython"withthehelpofMaximilianoSoler.

CristianBermudezSernasays:

I am student of Telecommunications engineering at the University of Antioquia


(Colombia).Months ago,i startedtolearn Pythonand foundthis wonderfulbook,
soivolunteeredtogettheSpanishtranslation.

23.23.Swedish
MikaelJacobsson(leochingkwake@gmail.com)hasvolunteeredtotranslatethebooktoSwedish.

23.24.Turkish
http://www.swaroopch.com/notes/python/

163/165

1/4/2015

AByteofPython

TrkerSEZER(tsezer@btturk.net)andBugraCakir(bugracakir@gmail.com)havevolunteeredto
translatethebooktoTurkish."WhereisTurkishversion?Bitsedeokusak."

http://www.swaroopch.com/notes/python/

164/165

1/4/2015

AByteofPython

24.TranslationHowto
1. Thefullsourceofthebookisavailablefromhttps://github.com/swaroopch/byte_of_python.
2. Pleaseforktherepository (https://help.github.com/articles/forkarepo).
3. Then,fetchtherepositorytoyourcomputer.YouneedtoknowhowtouseGit (http://www.gitscm.com)
todothat.
4. ReadAsciiDocsyntaxquickreference (http://asciidoctor.org/docs/asciidocsyntaxquickreference/).
5. Starteditingthe .asciidoc filestotranslatetoyourlocallanguage.
6. Run sourcecommands.bash anduse make_html , make_pdf ,etc.togenerateoutputfromthe
AsciiDocsources.

1.theauthoroftheamazing'BeginningPerl'book
2.Useatuple(youcanfindalistofallpunctuationmarkshere
(http://grammar.ccc.commnet.edu/grammar/marks/marks.htm)
)toholdalltheforbiddencharacters,thenusethemembershiptesttodeterminewhetheracharactershouldbe
removedornot,i.e.forbidden=( ! , ? , . ,
).
3.Createaclasstorepresentthepersonsinformation.Useadictionarytostorepersonobjectswiththeirnameas
thekey.Usethepicklemoduletostoretheobjectspersistentlyonyourharddisk.Usethedictionarybuiltin
methodstoadd,deleteandmodifythepersons.

Lastupdated2014101217:56:27IST

http://www.swaroopch.com/notes/python/

165/165

Vous aimerez peut-être aussi