165
1/4/2015 A Byte of Python http://www.swaroopch.com/notes/python/ 1/165 A Byte of Python Swaroop C H [email protected]

A Byte of Python.pdf

Embed Size (px)

DESCRIPTION

A Byte of Python.pdf

Citation preview

  • 1/4/2015 AByteofPython

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

    AByteofPython

    [email protected]

    mailto:[email protected]

  • 1/4/2015 AByteofPython

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

    TableofContents

    1.Welcome2.Dedication3.Preface4.Introduction5.Installation6.FirstSteps7.Basics8.OperatorsandExpressions9.ControlFlow10.Functions11.Modules12.DataStructures13.ProblemSolving14.ObjectOrientedProgramming15.InputandOutput16.Exceptions17.StandardLibrary18.More19.Appendix:FLOSS20.Appendix:Colophon21.Appendix:HistoryLesson22.Appendix:RevisionHistory23.Translations24.TranslationHowto

  • 1/4/2015 AByteofPython

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

    "AByteofPython"isafreebookonprogrammingusingthePythonlanguage.ItservesasatutorialorguidetothePythonlanguageforabeginneraudience.Ifallyouknowaboutcomputersishowtosavetextfiles,thenthisisthebookforyou.

  • 1/4/2015 AByteofPython

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

    1.Welcome

    1.1.WhoreadsAByteofPython?Herearewhatpeoplearesayingaboutthebook:

    ThisisthebestbeginnerstutorialIveeverseen!Thankyouforyoureffort.

    WaltMichalik

    Thebestthingifoundwas"AByteofPython",whichissimplyabrilliantbookfor

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

    examples.

    JoshuaRobin

    Excellentgentleintroductiontoprogramming#Pythonforbeginners

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

    Bestnewbieguidetopython

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

    starttolovepythonwitheverysinglepageread

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

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

    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 readinga Byte of python.Awesome work. And that too for free.

    Highlyrecommendedforaspiringpythonistas.

    Mangesh (https://twitter.com/mangeshnanoti/status/225680668867321857)

    https://twitter.com/HerbertFeutl/status/11901471389913088https://twitter.com/Dili_mathilakam/status/220033783066411008https://twitter.com/BiologistJohn/statuses/194726001803132928https://twitter.com/mangeshnanoti/status/225680668867321857mailto:[email protected]:[email protected]://twitter.com/ShanRajasekaran/status/268910645842423809https://twitter.com/nickaigi/status/175508815729541120

  • 1/4/2015 AByteofPython

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

    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

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

    Thank youso much forwriting A ByteOf Python. I just started learninghow to

    code two daysago and Imalready buildingsomesimple games.Your guidehas

    beenadreamandIjustwantedtoletyouknowhowvaluableithasbeen.

    Franklin

    Im fromDayanandasagarCollegeof Engineering (7th sem,CSE).Firstly iwant

    to say thatyourbook "Thebyteof python" is toogooda book fora 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 mygratitude to you for writing yourbook "AByte of Python", I already

    hadknowledgeof3programminglangaguesC,JavaandJavascript,andPython

    wasbyfar theeasiest langagueIhaveever learned,and thatwasmainlybecause

    yourbookwas fantasticandmade learningpythonverysimpleand interesting. It

    isoneofthebestwrittenandeasyto followprogrammingbooks Ihaveeverread.

    Congratulationsandkeepupthegreatwork.

    Matt

    Hi, ImfromDominicanRepublic.Myname isPavel, recentlyI readyourbookA

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

    examples.Yourbookisofgreathelpfornewbieslikeme

    PavelSimo

    https://twitter.com/YuvrajPoudyal/status/448050415356346368mailto:[email protected]://apas.gr/2010/04/27/learning-python/

  • 1/4/2015 AByteofPython

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

    Iam astudent fromChina, Now ,Ihave readyoubookAbyteofPython, Oh its

    beautiful.Thebookisverysimplebutcanhelpall the first learnners.YouknowI

    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 itsnot onlya goodchoice its mustuse thePython.MyEnglish isnot very

    well, the email to you, i just wanna thank you! Best Wishes for you and your

    family.

    RoyLau

    I recently finishedreading Byte of Python,and I thought I reallyought 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, secondedition, 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 themessagedowntoa level thatbeginnerscanunderstandandnot

    everyonecan.

    JosephDuarte

    I love your book! It is the greatest Python tutorial ever, and a very useful

    reference.Brilliant,atruemasterpiece!Keepupthegoodwork!

    ChrisAndrSommerseth

    mailto:[email protected]:[email protected]

  • 1/4/2015 AByteofPython

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

    Firstof all, Iwant to say thanks toyou for thisgreate book. I think it is agood

    bookforthosewhoarelookingforabeginnerstutorialforPython.

    It isabouttwoor thereyearsago, I think,when Ifirstheardof 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 Icanread thewholebookwithoutmydictionaryathand.Ofcourse,

    itallduestoyourefforttomakethisbookaneasytounderstandone.

    myd7349 (https://github.com/swaroopch/byte_of_python/pull/13)

    Im justemailingyou to thankyou forwritingByteofPythononline. Ihadbeen

    attempting Python for a few months prior to stumbling across your book, and

    althoughImadelimitedsuccesswithpyGame,Inevercompletedaprogram.

    Thankstoyoursimplificationofthecategories,Pythonactuallyseemsareachable

    goal. It seems like Ihave finally learned the foundationsand Ican continue into

    myrealgoal,gamedevelopment.

    Onceagain, thanksVERYmuch forplacingsuchastructuredandhelpfulguideto

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

    understandingwheretwotextbookshadfailed.

    MattGallivan

    mailto:[email protected]://github.com/swaroopch/byte_of_python/pull/13

  • 1/4/2015 AByteofPython

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

    Iwould like to thank you foryourbookAByteofPythonwhich imyself find the

    bestway to learn python. I ama 15yearold i live inegypt myname isAhmed.

    Pythonwasmysecondprogramminglanguagei learnvisualbasic6at schoolbut

    didntenjoy it,however i really enjoyed learningpython. Imade theaddressbook

    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

    starton learning javaand if youcan tellme where to find a tutorialas goodas

    yoursforjavathatwouldhelpmealot.Thanx.

    AhmedMohammed

    A wonderful resource for beginners wanting to learn more about Python is the

    110pagePDF tutorialAByteofPythonbySwaroopCH.It iswellwritten,easy

    tofollow,andmaybethebestintroductiontoPythonprogrammingavailable.

    DrewAmes (http://www.linux.com/feature/126522)

    Yesterday I got throughmost 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"Cananyonesuggestagood, inexpensiveresourcefor

    learningthebasicsofPython?")

    JustinLoveTrue (http://www.facebook.com/pythonlang/posts/406873916788)

    TheBookByteofpythonwasveryhelpful..Thanksbigtime:)

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

    http://www.linux.com/feature/126522http://paxmodept.com/telesto/blogitem.htm?id=627mailto:[email protected]://www.facebook.com/pythonlang/posts/406873916788https://twitter.com/a_chinmay/status/258822633741762560http://twitter.com/suren/status/12840485454

  • 1/4/2015 AByteofPython

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

    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#andJava.Theveryreason Iwanted to learnPythonis its

    popular (peopleare talkingabout it) andpowerful (reality).Thisbookwrittenby

    Mr. Swaroop is a very good guide for both brandnew programmers and new

    pythonprogrammers.Took10halfdaystogothroughit.GreatHelp!

    FangBiyi(PhDCandidateECE,MichiganStateUniversity)

    Thankyoueversomuchforthisbook!!

    Thisbook clearedup manyquestions I hadaboutcertain aspectsof Pythonsuch

    asobjectorientedprogramming.

    Idonot feel like anexpertatOObut Iknow thisbookhelped meona first step

    ortwo.

    Ihavenowwrittenseveralpythonprograms thatactuallydoreal thingsformeas

    a system administrator. They are all procedural oriented but they are small by

    mostpeoplesstandards.

    Again,thanksforthisbook.Thankyouforhavingitontheweb.

    Bob

    mailto:[email protected]://twitter.com/Pagal_e_azam/statuses/242865885256232960http://stackoverflow.com/a/457785/4869

  • 1/4/2015 AByteofPython

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

    Ijustwanttothankyou forwritingthefirstbookonprogrammingIveeverreally

    read.Python isnowmyfirst language,andIcanjust imagineall thepossibilities.

    Sothankyouforgivingmethetools tocreatethings Ineverwouldhaveimagined

    Icoulddobefore.

    TheWalrus

    Iwantedto thankyou forwritingAByteOfPython(2&3Versions). Ithasbeen

    invaluabletomylearningexperienceinPython&Programmingingeneral.

    Needlesstosay,Iamabeginnerintheprogrammingworld,acoupleofmonthsof

    selfstudyuptothispoint.Ihadbeenusingyoutube tutorials&someotheronline

    tutorials includingother freebooks. Idecided todig intoyour bookyesterday,&

    Ive learned more on the first few pages than any other book or tutorial. A few

    thingsIhadbeenconfusedabout,wereclearedrightupwithaGREATexample&

    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

  • 1/4/2015 AByteofPython

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

    Iwroteyouback in2011and Iwas justgetting into Pythonandwanted to thankyou for your tutorial "A Byte of Python". Without it, I would have fallen by thewayside. 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

    myselfanadvancedprogrammerbyanystretchbutInoticetheoccasionalrequest

    forassistancenowfromotherssinceI startedusing it.Idiscovered,while reading

    "Byte"why IhadceasedstudyingCandC[]+and itwasbecausethebookgiven

    to me started out with an example containing an augmented assignment. Of

    course, there wasno explanation for thisarrangement ofoperators and I fellon

    myhead trying tomakesenseofwhatwasonthewrittenpage. As I recallitwas

    amost frustratingexercisewhich Ieventuallyabandoned.Doesn'tmeanCorC+

    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

    whichisanessentialpartofanyinstruction.Justascomputerswillnotbeableto

    understandacomputerwordorcomputersymbol 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 areno definitions. You get a "blue

    screen"as itwereineithercase.Thesolution is simple, though:find thewordor

    symbolandget theproperdefinitionor symbolandloandbehold,thecomputeror

    studentcanproceed.Yourbookwassowellputtogether that Ifoundverylittle in

    it I couldnt grasp. So, thank you. I encourage you to continue to include full

    definitionsofterms.ThedocumentationwithPython isgood,onceyouknow, (the

    examples are its strength from what I see) but in many cases it seems that you

    have to know in order to understand thedocumentation which to mymind isnot

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

    Australia, some in the Caribbean and yet others in the US. It fills a niche no

    othersdo.Ihopeyouaredoingwellandwishyouallthesuccessinthefuture.

    Nick

  • 1/4/2015 AByteofPython

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

    hey, this isankush(19). Iwas facingagreatdifficulty to startwithpython. I tried

    a lot ofbooksbut allwerebulkier andnot targetoriented and then i found this

    lovelyone,whichmademelovepythoninnotime.Thanksalotfor this"beautiful

    pieceofbook".

    Ankush

    I would like to thank you for your excellent guide on Python. I am a molecular

    biologist (with littleprogrammingbackground)and formywork Ineed tohandle

    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 suchaguide is freelyavailable isaclear sign that the forcesofevilarenot

    yetrulingtheworld!:)

    Luca

    Since this is going to be the first language you learn, you should use A Byte of

    Python.It reallygivesaproper introductionintoprogramminginPythonand itis

    pacedwell enough for the averagebeginner.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

    singlepage wasboring. Iwant tounderstand theOrca screenreader code.Your

    bookhashopefullyequippedmeforit.

    http://www.overclock.net/t/1177951/want-to-learn-programming-where-do-i-start#post_15837176

  • 1/4/2015 AByteofPython

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

    Dattatray

    Hi, 'A byte of python' is really a good reading for python beginners. So, again,

    NICEWORK!

    im a4 yearsexperienced Java&Cdeveloper fromChina. Recently, i want to do

    someworkonzimwikinoteprojectwhichusespygtktoimplement.

    i readyourbook in6days,and icanreadand writepythoncodeexamplesnow.

    thx foryourcontribution.plzkeepyourenthusiasm tomake thisworldbetter, this

    isjustalittleencouragefromChina.YourreaderLee

    LEE

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

    EngineeringDepartmentofNationalTaiwanUniversity. Iwould liketo thankyou

    foryourgreatbook. Ithink itisnotonlyjusteasyto readbutalsocomprehensive

    and complete fora new comer ofPython. The reason I read your book is that I

    am starting to workon theGNU Radio framework. Yourbook letme catchmost

    ofimportantcoreideasandskillofPythonwithaminimumtime.

    Ialsosawthatyoudonotmind that readers sendyoua thanknoteinyourbook.

    SoIreallylikeyourbookandappreciateit.Thanks.

    IsenIChunChao

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

    1.2.AcademicCoursesThisbookis/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://dsnra.jpl.nasa.gov/software/Python/byte-of-python/output/byteofpython_html/http://www.few.vu.nl/~nsilvis/PPL/2007/index.htmlhttp://www.cs.ucdavis.edu/courses/exp_course_desc/10.htmlmailto:[email protected]:[email protected]

  • 1/4/2015 AByteofPython

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

    '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/600scintroductiontocomputerscienceandprogrammingspring2011/references/)

    'BasicprogrammingattheFacultyofSocialSciences,UniversityofLjubljana,Slovenia'Aleibernasays"I(andmypredecessor)havebeenusingyourbookasthemainliteratureforthiscourse"

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

    Thismeans:

    YouarefreetoSharei.e.tocopy,distributeandtransmitthisbook

    YouarefreetoRemixi.e.tomakechangestothisbook(especiallytranslations)

    Youarefreetouseitforcommercialpurposes

    Pleasenote:

    Pleasedonotsellelectronicorprintedcopiesofthebookunlessyouhaveclearlyandprominentlymentionedinthedescriptionthatthesecopiesarenotfromtheoriginalauthorofthisbook.

    Attributionmustbeshownintheintroductorydescriptionandfrontpageofthedocumentbylinkingbacktohttp://swaroopch.com/notes/pythonandclearlyindicatingthattheoriginaltextcanbefetchedfromthislocation.

    http://www.msu.edu/~ashton/classes/825/index.htmlhttp://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00sc-introduction-to-computer-science-and-programming-spring-2011/references/http://www.cs.bu.edu/courses/cs108/materials.htmlmailto:[email protected]://homepages.inf.ed.ac.uk/ewan/masws/http://www.people.fas.harvard.edu/~preshman/python_winter.htmlhttp://www.comp.leeds.ac.uk/acom1900/http://gentry.metr.ou.edu/byteofpython/http://creativecommons.org/licenses/by-sa/4.0/http://swaroopch.com/notes/python

  • 1/4/2015 AByteofPython

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

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

    1.4.ReadNowYoucanreadthebookonlineathttp://swaroopch.com/notes/python

    1.5.BuyTheBookAprintedhardcopyofthebookcanbepurchasedathttp://swaroopch.com/buybookforyourofflinereadingpleasure,andtosupportthecontinueddevelopmentandimprovementofthisbook.

    1.6.DownloadPDF (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.ReadthebookinyournativelanguageIfyouareinterestedinreadingorcontributingtranslationsofthisbooktootherhumanlanguages,pleaseseeTranslations.

    http://files.swaroopch.com/python/byte_of_python.pdfhttp://www.opensource.org/licenses/bsd-license.phphttp://swaroopch.com/buybookhttp://swaroopch.com/buybookhttp://files.swaroopch.com/python/byte_of_python.epubhttp://swaroopch.com/notes/pythonhttp://files.swaroopch.com/python/byte_of_python.mobihttps://github.com/swaroopch/byte_of_python

  • 1/4/2015 AByteofPython

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

    2.DedicationToKalyanVarma (http://www.kalyanvarma.net/)andmanyotherseniorsatPESIT (http://www.pes.edu/)whointroducedustoGNU/Linuxandtheworldofopensource.

    TothememoryofAtulChitnis (http://www.nextbigwhat.com/atulchitnisobituary297/),afriendandguidewhoshallbemissedgreatly.

    TothepioneerswhomadetheInternethappen (http://www.ibiblio.org/pioneers/index.html).Thisbookwasfirstwrittenin2003.Itstillremainspopular,thankstothenatureofsharingknowledgeontheInternetasenvisionedbythepioneers.

    http://www.nextbigwhat.com/atul-chitnis-obituary-297/http://www.ibiblio.org/pioneers/index.htmlhttp://www.kalyanvarma.net/http://www.pes.edu/

  • 1/4/2015 AByteofPython

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

    3.PrefacePythonisprobablyoneofthefewprogramminglanguageswhichisbothsimpleandpowerful.Thisisgoodforbeginnersaswellasforexperts,andmoreimportantly,isfuntoprogramwith.Thisbookaimstohelpyoulearnthiswonderfullanguageandshowhowtogetthingsdonequicklyandpainlesslyineffect'TheAntivenomtoyourprogrammingproblems'.

    3.1.WhoThisBookIsForThisbookservesasaguideortutorialtothePythonprogramminglanguage.Itismainlytargetedatnewbies.Itisusefulforexperiencedprogrammersaswell.

    Theaimisthatifallyouknowaboutcomputersishowtosavetextfiles,thenyoucanlearnPythonfromthisbook.Ifyouhavepreviousprogrammingexperience,thenyoucanalsolearnPythonfromthisbook.

    Ifyoudohavepreviousprogrammingexperience,youwillbeinterestedinthedifferencesbetweenPythonandyourfavoriteprogramminglanguageIhavehighlightedmanysuchdifferences.Alittlewarningthough,Pythonissoongoingtobecomeyourfavoriteprogramminglanguage!

    3.2.OfficialWebsiteTheofficialwebsiteofthebookishttp://swaroopch.com/notes/pythonwhereyoucanreadthewholebookonline,downloadthelatestversionsofthebook,buyaprintedhardcopy(http://swaroopch.com/buybook)andalsosendmefeedback.

    3.3.SomethingToThinkAbout

    There are two waysof 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://swaroopch.com/buybookhttp://swaroopch.com/notes/python

  • 1/4/2015 AByteofPython

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

    4.IntroductionPythonisoneofthoserarelanguageswhichcanclaimtobebothsimpleandpowerful.Youwillfindyourselfpleasantlysurprisedtoseehoweasyitistoconcentrateonthesolutiontotheproblemratherthanthesyntaxandstructureofthelanguageyouareprogrammingin.

    TheofficialintroductiontoPythonis:

    Python isaneasy tolearn,powerfulprogramminglanguage. Ithasefficienthigh

    level data structures and a simple but effective approach to objectoriented

    programming. Pythons elegant syntax and dynamic typing, together with its

    interpretednature, make it an ideal language for scriptingand rapidapplication

    developmentinmanyareasonmostplatforms.

    Iwilldiscussmostofthesefeaturesinmoredetailinthenextsection.

    StorybehindthenameGuidovanRossum,thecreatorofthePythonlanguage,namedthelanguageaftertheBBCshow"MontyPythonsFlyingCircus".Hedoesntparticularlylikesnakesthatkillanimalsforfoodbywindingtheirlongbodiesaroundthemandcrushingthem.

    4.1.FeaturesofPythonSimple

    Pythonisasimpleandminimalisticlanguage.ReadingagoodPythonprogramfeelsalmostlikereadingEnglish,althoughverystrictEnglish!ThispseudocodenatureofPythonisoneofitsgreateststrengths.Itallowsyoutoconcentrateonthesolutiontotheproblemratherthanthelanguageitself.

    EasytoLearn

    Asyouwillsee,Pythonisextremelyeasytogetstartedwith.Pythonhasanextraordinarilysimplesyntax,asalreadymentioned.

    FreeandOpenSource

    PythonisanexampleofaFLOSS(Free/LibrandOpenSourceSoftware).Insimpleterms,youcanfreelydistributecopiesofthissoftware,readitssourcecode,makechangestoit,andusepiecesofitinnewfreeprograms.FLOSSisbasedontheconceptofacommunitywhichsharesknowledge.Thisis

  • 1/4/2015 AByteofPython

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

    oneofthereasonswhyPythonissogoodithasbeencreatedandisconstantlyimprovedbyacommunitywhojustwanttoseeabetterPython.

    HighlevelLanguage

    WhenyouwriteprogramsinPython,youneverneedtobotheraboutthelowleveldetailssuchasmanagingthememoryusedbyyourprogram,etc.

    Portable

    Duetoitsopensourcenature,Pythonhasbeenportedto(i.e.changedtomakeitworkon)manyplatforms.AllyourPythonprogramscanworkonanyoftheseplatformswithoutrequiringanychangesatallifyouarecarefulenoughtoavoidanysystemdependentfeatures.

    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)tocreategamesforyourcomputerandforiPhone,iPad,andAndroid.

    Interpreted

    Thisrequiresabitofexplanation.

    AprogramwritteninacompiledlanguagelikeCorC[]+isconvertedfromthesourcelanguagei.e.CorC+intoalanguagethatisspokenbyyourcomputer(binarycodei.e.0sand1s)usingacompilerwithvariousflagsandoptions.Whenyouruntheprogram,thelinker/loadersoftwarecopiestheprogramfromharddisktomemoryandstartsrunningit.

    Python,ontheotherhand,doesnotneedcompilationtobinary.Youjustruntheprogramdirectlyfromthesourcecode.Internally,Pythonconvertsthesourcecodeintoanintermediateformcalledbytecodesandthentranslatesthisintothenativelanguageofyourcomputerandthenrunsit.Allthis,actually,makesusingPythonmucheasiersinceyoudonthavetoworryaboutcompilingtheprogram,makingsurethattheproperlibrariesarelinkedandloaded,etc.ThisalsomakesyourPythonprogramsmuchmoreportable,sinceyoucanjustcopyyourPythonprogramontoanothercomputeranditjustworks!

    ObjectOriented

    Pythonsupportsprocedureorientedprogrammingaswellasobjectorientedprogramming.Inprocedureorientedlanguages,theprogramisbuiltaroundproceduresorfunctionswhicharenothingbutreusablepiecesofprograms.Inobjectorientedlanguages,theprogramisbuiltaroundobjects

    http://kivy.org/

  • 1/4/2015 AByteofPython

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

    whichcombinedataandfunctionality.PythonhasaverypowerfulbutsimplisticwayofdoingOOP,especiallywhencomparedtobiglanguageslikeC++orJava.

    Extensible

    Ifyouneedacriticalpieceofcodetorunveryfastorwanttohavesomepieceofalgorithmnottobeopen,youcancodethatpartofyourprograminCorC\++andthenuseitfromyourPythonprogram.

    Embeddable

    YoucanembedPythonwithinyourC/C\++programstogivescriptingcapabilitiesforyourprogramsusers.

    ExtensiveLibraries

    ThePythonStandardLibraryishugeindeed.Itcanhelpyoudovariousthingsinvolvingregularexpressions,documentationgeneration,unittesting,threading,databases,webbrowsers,CGI,FTP,email,XML,XMLRPC,HTML,WAVfiles,cryptography,GUI(graphicaluserinterfaces),andothersystemdependentstuff.Remember,allthisisalwaysavailablewhereverPythonisinstalled.ThisiscalledtheBatteriesIncludedphilosophyofPython.

    Besidesthestandardlibrary,therearevariousotherhighqualitylibrarieswhichyoucanfindatthePythonPackageIndex (http://pypi.python.org/pypi).

    Summary

    Pythonisindeedanexcitingandpowerfullanguage.IthastherightcombinationofperformanceandfeaturesthatmakewritingprogramsinPythonbothfunandeasy.

    4.2.Python2versus3Youcanignorethissectionifyourenotinterestedinthedifferencebetween"Pythonversion2"and"Pythonversion3".Butpleasedobeawareofwhichversionyouareusing.ThisbookiswrittenforPython2.

    Rememberthatonceyouhaveproperlyunderstoodandlearntouseoneversion,youcaneasilylearnthedifferencesandusetheotherone.ThehardpartislearningprogrammingandunderstandingthebasicsofPythonlanguageitself.Thatisourgoalinthisbook,andonceyouhaveachievedthatgoal,youcaneasilyusePython2orPython3dependingonyoursituation.

    FordetailsondifferencesbetweenPython2andPython3,see:

    ThefutureofPython2 (http://lwn.net/Articles/547191/)

    http://lwn.net/Articles/547191/http://pypi.python.org/pypi

  • 1/4/2015 AByteofPython

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

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

    4.3.WhatProgrammersSayYoumayfinditinterestingtoreadwhatgreathackerslikeESRhavetosayaboutPython:

    1. EricS.Raymondistheauthorof"TheCathedralandtheBazaar"andisalsothepersonwhocoinedthetermOpenSource.HesaysthatPythonhasbecomehisfavoriteprogramminglanguage(http://www.python.org/about/success/esr/).ThisarticlewastherealinspirationformyfirstbrushwithPython.

    2. BruceEckelistheauthorofthefamous'ThinkinginJava'and'ThinkinginC++'books.HesaysthatnolanguagehasmadehimmoreproductivethanPython.HesaysthatPythonisperhapstheonlylanguagethatfocusesonmakingthingseasierfortheprogrammer.Readthecompleteinterview(http://www.artima.com/intv/aboutme.html)formoredetails.

    3. PeterNorvigisawellknownLispauthorandDirectorofSearchQualityatGoogle(thankstoGuidovanRossumforpointingthatout).HesaysthatwritingPythonislikewritinginpseudocode(https://news.ycombinator.com/item?id=1803815).HesaysthatPythonhasalwaysbeenanintegralpartofGoogle.YoucanactuallyverifythisstatementbylookingattheGoogleJobs(http://www.google.com/jobs/index.html)pagewhichlistsPythonknowledgeasarequirementforsoftwareengineers.

    https://news.ycombinator.com/item?id=1803815http://www.artima.com/intv/aboutme.htmlhttp://www.python.org/about/success/esr/https://wiki.ubuntu.com/Python/3http://www.google.com/jobs/index.html

  • 1/4/2015 AByteofPython

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

    5.InstallationWhenwereferto"Python2"inthisbook,wewillbereferringtoanyversionofPythonequaltoorgreaterthanversion2.7 (https://www.python.org/downloads/).

    5.1.InstallationonWindowsVisithttps://www.python.org/downloads/anddownloadthelatestversion.TheinstallationisjustlikeanyotherWindowsbasedsoftware.

    CAUTIONWhenyouaregiventheoptionofuncheckingany"optional"components,dontuncheckany.

    5.1.1.DOSPrompt

    IfyouwanttobeabletousePythonfromtheWindowscommandlinei.e.theDOSprompt,thenyouneedtosetthePATHvariableappropriately.

    ForWindows2000,XP,2003,clickonControlPanelSystemAdvancedEnvironmentVariables.ClickonthevariablenamedPATHintheSystemVariablessection,thenselectEditandadd;C:\Python27 (pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Ofcourse,usetheappropriatedirectoryname.

    ForolderversionsofWindows,openthefile C:\AUTOEXEC.BAT andaddthelinePATH=%PATH%;C:\Python33 andrestartthesystem.ForWindowsNT,usetheAUTOEXEC.NTfile.

    ForWindowsVista:

    1. ClickStartandchooseControlPanel

    2. ClickSystem,ontherightyoullsee"Viewbasicinformationaboutyourcomputer"

    3. Ontheleftisalistoftasks,thelastofwhichisAdvancedsystemsettings.Clickthat.

    4. TheAdvancedtaboftheSystemPropertiesdialogboxisshown.ClicktheEnvironmentVariablesbuttononthebottomright.

    5. InthelowerboxtitledSystemVariablesscrolldowntoPathandclicktheEditbutton.

    6. Changeyourpathasneedbe.

    7. Restartyoursystem.VistadidntpickupthesystempathenvironmentvariablechangeuntilIrestarted.

    https://www.python.org/downloads/https://www.python.org/downloads/

  • 1/4/2015 AByteofPython

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

    ForWindows7and8:

    1. RightclickonComputerfromyourdesktopandselectPropertiesorclickStartandchooseControlPanelSystemandSecuritySystem.ClickonAdvancedsystemsettingsontheleftandthenclickontheAdvancedtab.AtthebottomclickonEnvironmentVariablesandunderSystemvariables,lookforthePATHvariable,selectandthenpressEdit.

    2. GototheendofthelineunderVariablevalueandappend ;C:\Python27 (pleaseverifythatthisfolderexists,itwillbedifferentfornewerversionsofPython)totheendofwhatisalreadythere.Ofcourse,usetheappropriatefoldername.

    3. Ifthevaluewas %SystemRoot%\system32; Itwillnowbecome%SystemRoot%\system32;C:\Python27

    4. ClickOKandyouaredone.Norestartisrequired,howeveryoumayhavetocloseandreopenthecommandline.

    5.1.2.RunningPythonpromptonWindows

    ForWindowsusers,youcanruntheinterpreterinthecommandlineifyouhavesetthe PATH variableappropriately.

    ToopentheterminalinWindows,clickthestartbuttonandclickRun.Inthedialogbox,typecmdandpress enter key.

    Then,typepythonandensuretherearenoerrors.

    5.2.InstallationonMacOSXForMacOSXusers,Pythonmustbeinstalledalready.

    Toverify,opentheterminalbypressing Command + Space keys(toopenSpotlightsearch),typeTerminalandpress enter key.Now,runpythonandensuretherearenoerrors.

    5.3.InstallationonGNU/LinuxForGNU/Linuxusers,Pythonmustbeinstalledalready.

    Toverify,opentheterminalbyopeningtheTerminalapplicationorbypressing Alt + F2 andenteringgnometerminal.Ifthatdoesntwork,pleasereferthedocumentationofyourparticularGNU/Linuxdistribution.Now,runpythonandensuretherearenoerrors.

    YoucanseetheversionofPythononthescreenbyrunning:

  • 1/4/2015 AByteofPython

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

    NOTE$ isthepromptoftheshell.Itwillbedifferentforyoudependingonthesettingsoftheoperatingsystemonyourcomputer,henceIwillindicatethepromptbyjustthe $symbol.

    CAUTIONOutputmaybedifferentonyourcomputer,dependingontheversionofPythonsoftwareinstalledonyourcomputer.

    5.4.SummaryFromnowon,wewillassumethatyouhavePythoninstalledonyoursystem.

    Next,wewillwriteourfirstPythonprogram.

    $pythonVPython2.7.6

  • 1/4/2015 AByteofPython

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

    6.FirstStepsWewillnowseehowtorunatraditional'HelloWorld'programinPython.Thiswillteachyouhowtowrite,saveandrunPythonprograms.

    TherearetwowaysofusingPythontorunyourprogramusingtheinteractiveinterpreterpromptorusingasourcefile.Wewillnowseehowtousebothofthesemethods.

    6.1.UsingTheInterpreterPromptOpentheterminalinyouroperatingsystem(asdiscussedpreviouslyintheInstallationchapter)andthenopenthePythonpromptbytypingpythonandpressing enter key.

    OnceyouhavestartedPython,youshouldsee >>> whereyoucanstarttypingstuff.ThisiscalledthePythoninterpreterprompt.

    AtthePythoninterpreterprompt,type:

    followedbythe enter key.YoushouldseethewordsHelloWorldprintedtothescreen.

    Hereisanexampleofwhatyoushouldbeseeing,whenusingaMacOSXcomputer.ThedetailsaboutthePythonsoftwarewilldifferbasedonyourcomputer,butthepartfromtheprompt(i.e.from >>>onwards)shouldbethesameregardlessoftheoperatingsystem.

    NoticethatPythongivesyoutheoutputofthelineimmediately!WhatyoujustenteredisasinglePythonstatement.Weuseprintto(unsurprisingly)printanyvaluethatyousupplytoit.Here,wearesupplyingthetexthelloworldandthisispromptlyprintedtothescreen.

    HowtoQuittheInterpreterPrompt

    print"HelloWorld"PYTHON

    $pythonPython2.7.6(default,Feb232014,16:08:15)[GCC4.2.1CompatibleAppleLLVM5.0(clang500.2.79)]ondarwinType"help","copyright","credits"or"license"formoreinformation.>>>print"helloworld"helloworld>>>

  • 1/4/2015 AByteofPython

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

    NOTEIfyouareusingaGNU/LinuxorOSXshell,youcanexittheinterpreterpromptbypressing ctrl + d orenteringexit()(note:remembertoincludetheparentheses,())followedbythe enter key.

    IfyouareusingtheWindowscommandprompt,press ctrl + z followedbytheenter key.

    6.2.ChoosingAnEditorWecannottypeoutourprogramattheinterpreterprompteverytimewewanttorunsomething,sowehavetosavetheminfilesandcanrunourprogramsanynumberoftimes.

    TocreateourPythonsourcefiles,weneedaneditorsoftwarewhereyoucantypeandsave.Agoodprogrammerseditorwillmakeyourlifeeasierinwritingthesourcefiles.Hence,thechoiceofaneditoriscrucialindeed.Youhavetochooseaneditorasyouwouldchooseacaryouwouldbuy.AgoodeditorwillhelpyouwritePythonprogramseasily,makingyourjourneymorecomfortableandhelpsyoureachyourdestination(achieveyourgoal)inamuchfasterandsaferway.

    OneoftheverybasicrequirementsissyntaxhighlightingwhereallthedifferentpartsofyourPythonprogramarecolorizedsothatyoucanseeyourprogramandvisualizeitsrunning.

    Ifyouhavenoideawheretostart,IwouldrecommendusingPyCharmEducationalEdition(https://www.jetbrains.com/pycharmeducational/)softwarewhichisavailableonWindows,MacOSXandGNU/Linux.Detailsinthenextsection.

    IfyouareusingWindows,donotuseNotepaditisabadchoicebecauseitdoesnotdosyntaxhighlightingandalsoimportantlyitdoesnotsupportindentationofthetextwhichisveryimportantinourcaseaswewillseelater.Goodeditorswillautomaticallydothis.

    Ifyouareanexperiencedprogrammer,thenyoumustbealreadyusingVim (http://www.vim.org)orEmacs(http://www.gnu.org/software/emacs/).Needlesstosay,thesearetwoofthemostpowerfuleditorsandyouwillbenefitfromusingthemtowriteyourPythonprograms.Ipersonallyusebothformostofmyprograms,andhaveevenwrittenanentirebookonVim (http://swaroopch.com/notes/vim).

    IncaseyouarewillingtotakethetimetolearnVimorEmacs,thenIhighlyrecommendthatyoudolearntouseeitherofthemasitwillbeveryusefulforyouinthelongrun.However,asImentionedbefore,beginnerscanstartwithPyCharmandfocusthelearningonPythonratherthantheeditoratthismoment.

    Toreiterate,pleasechooseapropereditoritcanmakewritingPythonprogramsmorefunandeasy.

    http://swaroopch.com/notes/vimhttp://www.vim.org/http://www.gnu.org/software/emacs/https://www.jetbrains.com/pycharm-educational/

  • 1/4/2015 AByteofPython

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

    6.3.PyCharmPyCharmEducationalEdition (https://www.jetbrains.com/pycharmeducational/)isafreeeditorwhichyoucanuseforwritingPythonprograms.

    WhenyouopenPyCharm,youllseethis,clickonCreateNewProject:

    SelectPurePython:

    https://www.jetbrains.com/pycharm-educational/

  • 1/4/2015 AByteofPython

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

    Changeuntitledtohelloworldasthelocationoftheproject,youshouldseedetailssimilartothis:

    ClicktheCreatebutton.

    RightclickonthehelloworldinthesidebarandselectNewPythonFile:

  • 1/4/2015 AByteofPython

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

    PyCharm>New>PythonFile

    Youwillbeaskedtotypethename,typehello:

  • 1/4/2015 AByteofPython

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

    PyCharmNewFiledialogbox

    Youcannowseeafileopenedforyou:

  • 1/4/2015 AByteofPython

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

    PyCharmhello.pyfile

    Deletethelinesthatarealreadypresent,andnowtypethefollowing:

    Nowrightclickonwhatyoutyped(withoutselectingthetext),andclickonRun'hello'.

    print"helloworld"PYTHON

  • 1/4/2015 AByteofPython

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

    PyCharmRun'hello'

    Youshouldnowseetheoutput(whatitprints)ofyourprogram:

  • 1/4/2015 AByteofPython

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

    PyCharmoutput

    Phew!Thatwasquiteafewstepstogetstarted,buthenceforth,everytimeweaskyoutocreateanewfile,remembertojustrightclickonhelloworldontheleftNewPythonFileandcontinuethesamestepstotypeandrunasshownabove.

    YoucanfindmoreinformationaboutPyCharminthePyCharmQuickstart(https://www.jetbrains.com/pycharmeducational/quickstart/)page.

    6.4.Vim1. InstallVim (http://www.vim.org)

    a. MacOSXusersshouldinstallmacvimpackageviaHomeBrew (http://brew.sh/)

    http://www.vim.org/http://brew.sh/https://www.jetbrains.com/pycharm-educational/quickstart/

  • 1/4/2015 AByteofPython

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

    b. Windowsusersshoulddownloadthe"selfinstallingexecutable"fromhttp://www.vim.org/download.php

    c. GNU/LinuxusersshouldgetVimfromtheirdistributionssoftwarerepositories,e.g.DebianandUbuntuuserscaninstallthevim (http://packages.ubuntu.com/saucy/vim)package.

    2. ReadtheVimasPythonIDE (http://blog.sontek.net/blog/detail/turningvimintoamodernpythonide)articlebyJohnMAnderson.

    3. Installjedivim (https://github.com/davidhalter/jedivim)pluginforautocompletion.

    6.5.Emacs1. InstallEmacs24 (http://www.gnu.org/software/emacs/).

    a. MacOSXusersshouldgetEmacsfromhttp://emacsformacosx.com

    b. WindowsusersshouldgetEmacsfromhttp://ftp.gnu.org/gnu/emacs/windows/

    c. GNU/LinuxusersshouldgetEmacsfromtheirdistributionssoftwarerepositories,e.g.DebianandUbuntuuserscaninstalltheemacs24 (http://packages.ubuntu.com/saucy/emacs24)package.

    2. InstallELPY (https://github.com/jorgenschaefer/elpy/wiki).

    6.6.UsingASourceFileNowletsgetbacktoprogramming.Thereisatraditionthatwheneveryoulearnanewprogramminglanguage,thefirstprogramthatyouwriteandrunisthe'HelloWorld'programallitdoesisjustsay

    'HelloWorld'whenyourunit.AsSimonCozens[1]says,itisthe"traditionalincantationtotheprogramminggodstohelpyoulearnthelanguagebetter."

    Startyourchoiceofeditor,enterthefollowingprogramandsaveitashello.py.

    IfyouareusingPyCharm,wehavealreadydiscussedhowtorunfromasourcefile.

    Forothereditors,openanewfilehello.pyandtypethis:

    Whereshouldyousavethefile?Toanyfolderforwhichyouknowthelocationofthefolder.Ifyoudontunderstandwhatthatmeans,createanewfolderandusethatlocationtosaveandrunallyourPythonprograms:

    /tmp/py onMacOSX

    print"helloworld"PYTHON

    http://blog.sontek.net/blog/detail/turning-vim-into-a-modern-python-idehttps://github.com/jorgenschaefer/elpy/wikihttp://www.vim.org/download.phphttp://packages.ubuntu.com/saucy/emacs24http://ftp.gnu.org/gnu/emacs/windows/http://packages.ubuntu.com/saucy/vimhttp://emacsformacosx.com/https://github.com/davidhalter/jedi-vimhttp://www.gnu.org/software/emacs/

  • 1/4/2015 AByteofPython

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

    /tmp/py onGNU/Linux

    C:\\py onWindows

    Tocreatetheabovefolder(fortheoperatingsystemyouareusing),usethemkdircommandintheterminal,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.pyhelloworld

  • 1/4/2015 AByteofPython

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

    Screenshotofrunningprograminterminal

    Ifyougottheoutputasshownabove,congratulations!youhavesuccessfullyrunyourfirstPythonprogram.Youhavesuccessfullycrossedthehardestpartoflearningprogramming,whichis,gettingstartedwithyourfirstprogram!

    Incaseyougotanerror,pleasetypetheaboveprogramexactlyasshownaboveandruntheprogramagain.NotethatPythoniscasesensitivei.e.printisnotthesameasPrintnotethelowercasepintheformerandtheuppercasePinthelatter.Also,ensuretherearenospacesortabsbeforethefirstcharacterineachlinewewillseewhythisisimportantlater.

    HowItWorks

    APythonprogramiscomposedofstatements.Inourfirstprogram,wehaveonlyonestatement.Inthisstatement,wecalltheprintstatementtowhichwesupplythetext"helloworld".

    6.7.GettingHelp

  • 1/4/2015 AByteofPython

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

    IfyouneedquickinformationaboutanyfunctionorstatementinPython,thenyoucanusethebuiltinhelpfunctionality.Thisisveryusefulespeciallywhenusingtheinterpreterprompt.Forexample,runhelp('len') thisdisplaysthehelpforthelenfunctionwhichisusedtocountnumberofitems.

    TIP Pressqtoexitthehelp.

    Similarly,youcanobtaininformationaboutalmostanythinginPython.Usehelp()tolearnmoreaboutusinghelpitself!

    Incaseyouneedtogethelpforoperatorslikereturn,thenyouneedtoputthoseinsidequotessuchashelp('return') sothatPythondoesntgetconfusedonwhatweretryingtodo.

    6.8.SummaryYoushouldnowbeabletowrite,saveandrunPythonprogramsatease.

    NowthatyouareaPythonuser,letslearnsomemorePythonconcepts.

  • 1/4/2015 AByteofPython

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

    7.BasicsJustprintinghelloworldisnotenough,isit?Youwanttodomorethanthatyouwanttotakesomeinput,manipulateitandgetsomethingoutofit.WecanachievethisinPythonusingconstantsandvariables,andwelllearnsomeotherconceptsaswellinthischapter.

    7.1.CommentsCommentsareanytexttotherightofthe # symbolandismainlyusefulasnotesforthereaderoftheprogram.

    Forexample:

    or:

    Useasmanyusefulcommentsasyoucaninyourprogramto:

    explainassumptions

    explainimportantdecisions

    explainimportantdetails

    explainproblemsyouretryingtosolve

    explainproblemsyouretryingtoovercomeinyourprogram,etc.

    Codetellsyouhow,commentsshouldtellyouwhy(http://www.codinghorror.com/blog/2006/12/codetellsyouhowcommentstellyouwhy.html).

    Thisisusefulforreadersofyourprogramsothattheycaneasilyunderstandwhattheprogramisdoing.Remember,thatpersoncanbeyourselfaftersixmonths!

    7.2.LiteralConstantsAnexampleofaliteralconstantisanumberlike 5 , 1.23 ,orastringlike 'Thisisastring' or"Itsastring!" .

    print'helloworld'#NotethatprintisastatementPYTHON

    #Notethatprintisastatementprint'helloworld'

    PYTHON

    http://www.codinghorror.com/blog/2006/12/code-tells-you-how-comments-tell-you-why.html

  • 1/4/2015 AByteofPython

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

    Itiscalledaliteralbecauseitisliteralyouuseitsvalueliterally.Thenumber 2 alwaysrepresentsitselfandnothingelseitisaconstantbecauseitsvaluecannotbechanged.Hence,allthesearereferredtoasliteralconstants.

    7.3.NumbersNumbersaremainlyoftwotypesintegersandfloats.

    Anexamplesofanintegeris 2 whichisjustawholenumber.

    Examplesoffloatingpointnumbers(orfloatsforshort)are 3.23 and 52.3E4 .TheEnotationindicatespowersof10.Inthiscase, 52.3E4 means52.3*10^4^.

    NOTENoteforExperiencedProgrammers

    Thereisnoseparatelongtype.Theinttypecanbeanintegerofanysize.

    7.4.StringsAstringisasequenceofcharacters.Stringsarebasicallyjustabunchofwords.

    YouwillbeusingstringsinalmosteveryPythonprogramthatyouwrite,sopayattentiontothefollowingpart.

    7.4.1.SingleQuote

    Youcanspecifystringsusingsinglequotessuchas 'Quotemeonthis' .

    Allwhitespacei.e.spacesandtabs,withinthequotes,arepreservedasis.

    7.4.2.DoubleQuotes

    Stringsindoublequotesworkexactlythesamewayasstringsinsinglequotes.Anexampleis "Whatsyourname?" .

    7.4.3.TripleQuotes

    Youcanspecifymultilinestringsusingtriplequotes( """ or ''' ).Youcanusesinglequotesanddoublequotesfreelywithinthetriplequotes.Anexampleis:

  • 1/4/2015 AByteofPython

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

    7.4.4.StringsAreImmutable

    Thismeansthatonceyouhavecreatedastring,youcannotchangeit.Althoughthismightseemlikeabadthing,itreallyisnt.Wewillseewhythisisnotalimitationinthevariousprogramsthatweseelateron.

    NOTENoteforC/C++Programmers

    ThereisnoseparatechardatatypeinPython.ThereisnorealneedforitandIamsureyouwontmissit.

    NOTENoteforPerl/PHPProgrammers

    Rememberthatsinglequotedstringsanddoublequotedstringsarethesametheydonotdifferinanyway.

    7.4.5.Theformatmethod

    Sometimeswemaywanttoconstructstringsfromotherinformation.Thisiswheretheformat()methodisuseful.

    Savethefollowinglinesasafilestr_format.py:

    Output:

    HowItWorks

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

    PYTHON

    age=20name='Swaroop'

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

    PYTHON

    $pythonstr_format.pySwaroopwas20yearsoldwhenhewrotethisbookWhyisSwaroopplayingwiththatpython?

  • 1/4/2015 AByteofPython

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

    Astringcanusecertainspecificationsandsubsequently,theformatmethodcanbecalledtosubstitutethosespecificationswithcorrespondingargumentstotheformatmethod.

    Observethefirstusagewhereweuse{0}andthiscorrespondstothevariablenamewhichisthefirstargumenttotheformatmethod.Similarly,thesecondspecificationis{1}correspondingtoagewhichisthesecondargumenttotheformatmethod.NotethatPythonstartscountingfrom0whichmeansthatfirstpositionisatindex0,secondpositionisatindex1,andsoon.

    Noticethatwecouldhaveachievedthesameusingstringconcatenation:

    butthatismuchuglieranderrorprone.Second,theconversiontostringwouldbedoneautomaticallybytheformatmethodinsteadoftheexplicitconversiontostringsneededinthiscase.Third,whenusingtheformatmethod,wecanchangethemessagewithouthavingtodealwiththevariablesusedandviceversa.

    Alsonotethatthenumbersareoptional,soyoucouldhavealsowrittenas:

    whichwillgivethesameexactoutputasthepreviousprogram.

    WhatPythondoesintheformatmethodisthatitsubstituteseachargumentvalueintotheplaceofthespecification.Therecanbemoredetailedspecificationssuchas:

    Output:

    name+'is'+str(age)+'yearsold'PYTHON

    age=20name='Swaroop'

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

    PYTHON

    #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

  • 1/4/2015 AByteofPython

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

    Sincewearediscussingformatting,notethatprintalwaysendswithaninvisible"newline"character(\n)sothatrepeatedcallstoprintwillallprintonaseparatelineeach.Topreventthisnewlinecharacterfrombeingprinted,youcanendthestatementwithacomma:

    Outputis:

    7.4.6.EscapeSequences

    Suppose,youwanttohaveastringwhichcontainsasinglequote( ' ),howwillyouspecifythisstring?Forexample,thestringis "Whatsyourname?" .Youcannotspecify 'Whatsyourname?'becausePythonwillbeconfusedastowherethestringstartsandends.So,youwillhavetospecifythatthissinglequotedoesnotindicatetheendofthestring.Thiscanbedonewiththehelpofwhatiscalledanescapesequence.Youspecifythesinglequoteas \' :noticethebackslash.Now,youcanspecifythestringas 'What'syourname?' .

    Anotherwayofspecifyingthisspecificstringwouldbe "Whatsyourname?" i.e.usingdoublequotes.Similarly,youhavetouseanescapesequenceforusingadoublequoteitselfinadoublequotedstring.Also,youhavetoindicatethebackslashitselfusingtheescapesequence \\ .

    Whatifyouwantedtospecifyatwolinestring?Onewayistouseatriplequotedstringasshownpreviouslyoryoucanuseanescapesequenceforthenewlinecharacter\ntoindicatethestartofanewline.Anexampleis:

    Anotherusefulescapesequencetoknowisthetab:\t.TherearemanymoreescapesequencesbutIhavementionedonlythemostusefuloneshere.

    Onethingtonoteisthatinastring,asinglebackslashattheendofthelineindicatesthatthestringiscontinuedinthenextline,butnonewlineisadded.Forexample:

    0.333___hello___SwaroopwroteAByteofPython

    print"a",print"b",

    PYTHON

    ab

    'Thisisthefirstline\nThisisthesecondline'PYTHON

  • 1/4/2015 AByteofPython

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

    isequivalentto

    7.4.7.RawString

    Ifyouneedtospecifysomestringswherenospecialprocessingsuchasescapesequencesarehandled,thenwhatyouneedistospecifyarawstringbyprefixingrorRtothestring.Anexampleis:

    NOTE

    NoteforRegularExpressionUsers

    Alwaysuserawstringswhendealingwithregularexpressions.Otherwise,alotofbackwhackingmayberequired.Forexample,backreferencescanbereferredtoas'\\1' or r'\1' .

    7.5.VariableUsingjustliteralconstantscansoonbecomeboringweneedsomewayofstoringanyinformationandmanipulatethemaswell.Thisiswherevariablescomeintothepicture.Variablesareexactlywhatthenameimpliestheirvaluecanvary,i.e.,youcanstoreanythingusingavariable.Variablesarejustpartsofyourcomputersmemorywhereyoustoresomeinformation.Unlikeliteralconstants,youneedsomemethodofaccessingthesevariablesandhenceyougivethemnames.

    7.6.IdentifierNamingVariablesareexamplesofidentifiers.Identifiersarenamesgiventoidentifysomething.Therearesomerulesyouhavetofollowfornamingidentifiers:

    Thefirstcharacteroftheidentifiermustbealetterofthealphabet(uppercaseASCIIorlowercaseASCIIorUnicodecharacter)oranunderscore( _ ).

    Therestoftheidentifiernamecanconsistofletters(uppercaseASCIIorlowercaseASCIIorUnicodecharacter),underscores( _ )ordigits(09).

    Identifiernamesarecasesensitive.Forexample, myname and myName arenotthesame.Notethelowercase n intheformerandtheuppercase N inthelatter.

    "Thisisthefirstsentence.\Thisisthesecondsentence."

    PYTHON

    "Thisisthefirstsentence.Thisisthesecondsentence."PYTHON

    r"Newlinesareindicatedby\n"PYTHON

  • 1/4/2015 AByteofPython

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

    Examplesofvalididentifiernamesare i , name_2_3 .Examplesofinvalididentifiernamesare2things , thisisspacedout , myname and >a1b2_c3 .

    7.7.DataTypesVariablescanholdvaluesofdifferenttypescalleddatatypes.Thebasictypesarenumbersandstrings,whichwehavealreadydiscussed.Inlaterchapters,wewillseehowtocreateourowntypesusingclasses.

    7.8.ObjectRemember,Pythonreferstoanythingusedinaprogramasanobject.Thisismeantinthegenericsense.Insteadofsaying"thesomething"',wesay"theobject".

    NOTENoteforObjectOrientedProgrammingusers

    Pythonisstronglyobjectorientedinthesensethateverythingisanobjectincludingnumbers,stringsandfunctions.

    Wewillnowseehowtousevariablesalongwithliteralconstants.Savethefollowingexampleandruntheprogram.

    7.9.HowtowritePythonprogramsHenceforth,thestandardproceduretosaveandrunaPythonprogramisasfollows:

    7.10.ForPyCharm1. OpenPyCharm.

    2. Createnewfilewiththefilenamementioned.

    3. Typetheprogramcodegivenintheexample.

    4. Rightclickandrunthecurrentfile.

    Wheneveryouhavetoprovidecommandlinearguments,clickonRunEditConfigurationsandtypetheargumentsintheScriptparameters:sectionandclicktheOKbutton:

  • 1/4/2015 AByteofPython

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

    NOTE

    PyCharmcommandlinearguments

    7.11.Forothereditors1. Openyoureditorofchoice.

    2. Typetheprogramcodegivenintheexample.

    3. Saveitasafilewiththefilenamementioned.

    4. Runtheinterpreterwiththecommandpythonprogram.pytoruntheprogram.

    7.12.Example:UsingVariablesAndLiteralConstantsTypeandrunthefollowingprogram:

  • 1/4/2015 AByteofPython

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

    Output:

    HowItWorks

    Hereshowthisprogramworks.First,weassigntheliteralconstantvalue5tothevariableiusingtheassignmentoperator( = ).Thislineiscalledastatementbecauseitstatesthatsomethingshouldbedoneandinthiscase,weconnectthevariablenameitothevalue5.Next,weprintthevalueofiusingtheprintstatementwhich,unsurprisingly,justprintsthevalueofthevariabletothescreen.

    Thenweadd1tothevaluestorediniandstoreitback.Wethenprintitandexpectedly,wegetthevalue6.

    Similarly,weassigntheliteralstringtothevariablesandthenprintit.

    NOTENoteforstaticlanguageprogrammers

    Variablesareusedbyjustassigningthemavalue.Nodeclarationordatatypedefinitionisneeded/used.

    7.13.LogicalAndPhysicalLineAphysicallineiswhatyouseewhenyouwritetheprogram.AlogicallineiswhatPythonseesasasinglestatement.Pythonimplicitlyassumesthateachphysicallinecorrespondstoalogicalline.

    Anexampleofalogicallineisastatementlike print'helloworld' ifthiswasonalinebyitself(asyouseeitinaneditor),thenthisalsocorrespondstoaphysicalline.

    Implicitly,Pythonencouragestheuseofasinglestatementperlinewhichmakescodemorereadable.

    #Filename:var.pyi=5printii=i+1printi

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

    PYTHON

    56Thisisamultilinestring.Thisisthesecondline.

  • 1/4/2015 AByteofPython

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

    Ifyouwanttospecifymorethanonelogicallineonasinglephysicalline,thenyouhavetoexplicitlyspecifythisusingasemicolon( ; )whichindicatestheendofalogicalline/statement.Forexample:

    iseffectivelysameas

    whichisalsosameas

    andsameas

    However,Istronglyrecommendthatyousticktowritingamaximumofasinglelogicallineoneachsinglephysicalline.Theideaisthatyoushouldneverusethesemicolon.Infact,IhaveneverusedorevenseenasemicoloninaPythonprogram.

    Thereisonekindofsituationwherethisconceptisreallyuseful:ifyouhavealonglineofcode,youcanbreakitintomultiplephysicallinesbyusingthebackslash.Thisisreferredtoasexplicitlinejoining:

    Output:

    Similarly,

    i=5printi

    PYTHON

    i=5;printi;

    PYTHON

    i=5;printi;PYTHON

    i=5;printiPYTHON

    s='Thisisastring.\Thiscontinuesthestring.'prints

    PYTHON

    Thisisastring.Thiscontinuesthestring.

  • 1/4/2015 AByteofPython

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

    isthesameas

    Sometimes,thereisanimplicitassumptionwhereyoudontneedtouseabackslash.Thisisthecasewherethelogicallinehasastartingparentheses,startingsquarebracketsorastartingcurlybracesbutnotanendingone.Thisiscalledimplicitlinejoining.Youcanseethisinactionwhenwewriteprogramsusinglistsinlaterchapters.

    7.14.IndentationWhitespaceisimportantinPython.Actually,whitespaceatthebeginningofthelineisimportant.Thisiscalledindentation.Leadingwhitespace(spacesandtabs)atthebeginningofthelogicallineisusedtodeterminetheindentationlevelofthelogicalline,whichinturnisusedtodeterminethegroupingofstatements.

    Thismeansthatstatementswhichgotogethermusthavethesameindentation.Eachsuchsetofstatementsiscalledablock.Wewillseeexamplesofhowblocksareimportantinlaterchapters.

    Onethingyoushouldrememberisthatwrongindentationcangiverisetoerrors.Forexample:

    Whenyourunthis,yougetthefollowingerror:

    Noticethatthereisasinglespaceatthebeginningofthesecondline.TheerrorindicatedbyPythontellsusthatthesyntaxoftheprogramisinvalidi.e.theprogramwasnotproperlywritten.Whatthismeanstoyouisthatyoucannotarbitrarilystartnewblocksofstatements(exceptforthedefaultmainblockwhich

    print\i

    PYTHON

    printiPYTHON

    i=5#Errorbelow!Noticeasinglespaceatthestartofthelineprint'Valueis',iprint'Irepeat,thevalueis',i

    PYTHON

    File"whitespace.py",line5print'Valueis',i^IndentationError:unexpectedindent

  • 1/4/2015 AByteofPython

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

    youhavebeenusingallalong,ofcourse).CaseswhereyoucanusenewblockswillbedetailedinlaterchapterssuchastheControlFlow.

    Howtoindent

    Usefourspacesforindentation.ThisistheofficialPythonlanguagerecommendation.Goodeditorswillautomaticallydothisforyou.Makesureyouuseaconsistentnumberofspacesforindentation,otherwiseyourprogramwillshowerrors.

    NOTENotetostaticlanguageprogrammers

    Pythonwillalwaysuseindentationforblocksandwillneverusebraces.Run fromfutureimportbraces tolearnmore.

    7.15.SummaryNowthatwehavegonethroughmanynittygrittydetails,wecanmoveontomoreinterestingstuffsuchascontrolflowstatements.Besuretobecomecomfortablewithwhatyouhavereadinthischapter.

  • 1/4/2015 AByteofPython

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

    8.OperatorsandExpressionsMoststatements(logicallines)thatyouwritewillcontainexpressions.Asimpleexampleofanexpressionis 2+3 .Anexpressioncanbebrokendownintooperatorsandoperands.

    Operatorsarefunctionalitythatdosomethingandcanberepresentedbysymbolssuchas + orbyspecialkeywords.Operatorsrequiresomedatatooperateonandsuchdataiscalledoperands.Inthiscase, 2and 3 aretheoperands.

    8.1.OperatorsWewillbrieflytakealookattheoperatorsandtheirusage.

    Notethatyoucanevaluatetheexpressionsgivenintheexamplesusingtheinterpreterinteractively.Forexample,totesttheexpression 2+3 ,usetheinteractivePythoninterpreterprompt:

    Hereisaquickoverviewoftheavailableoperators:

    + (plus)

    Addstwoobjects

    3+5 gives 8 . 'a'+'b' gives 'ab' .

    (minus)

    Givesthesubtractionofonenumberfromtheotherifthefirstoperandisabsentitisassumedtobezero.

    5.2 givesanegativenumberand 5024 gives 26 .

    *(multiply)

    Givesthemultiplicationofthetwonumbersorreturnsthestringrepeatedthatmanytimes.

    2*3 gives 6 . 'la'*3 gives 'lalala' .

    **(power)

    >>>2+35>>>3*515>>>

    PYTHON

  • 1/4/2015 AByteofPython

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

    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 .

    >1 gives 5 .

    11 isrepresentedinbitsby 1011 whichwhenrightshiftedby1bitgives 101`whichisthedecimal 5 .

    & (bitwiseAND)

    BitwiseANDofthenumbers

    5&3 gives 1 .

    | (bitwiseOR)

    BitwiseORofthenumbers

    5|3 gives 7

  • 1/4/2015 AByteofPython

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

    ^ (bitwiseXOR)

    BitwiseXORofthenumbers

    5 3 gives 6

    ~ (bitwiseinvert)

    Thebitwiseinversionofxis(x+1)

    ~5 gives 6 .Moredetailsathttp://stackoverflow.com/a/11810203

    < (lessthan)

    Returnswhetherxislessthany.Allcomparisonoperatorsreturn True or False .Notethecapitalizationofthesenames.

    5=3 returns True .

    == (equalto)

    Comparesiftheobjectsareequal

    x=2;y=2;x==y returns True .

    x='str';y='stR';x==y returns False .

    http://stackoverflow.com/a/11810203

  • 1/4/2015 AByteofPython

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

    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,Pythonwillnotevaluateysinceitknowsthatthelefthandsideofthe'and'expressionis False whichimpliesthatthewholeexpressionwillbe False irrespectiveoftheothervalues.Thisiscalledshortcircuitevaluation.

    or (booleanOR)

    Ifxis True ,itreturnsTrue,elseitreturnsevaluationofy

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

    8.2.ShortcutformathoperationandassignmentItiscommontorunamathoperationonavariableandthenassigntheresultoftheoperationbacktothevariable,hencethereisashortcutforsuchexpressions:

    canbewrittenas:

    Noticethat var=varoperationexpression becomes varoperation=expression .

    a=2a=a*3

    PYTHON

    a=2a*=3

    PYTHON

  • 1/4/2015 AByteofPython

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

    8.3.EvaluationOrderIfyouhadanexpressionsuchas 2+3*4 ,istheadditiondonefirstorthemultiplication?Ourhighschoolmathstellsusthatthemultiplicationshouldbedonefirst.Thismeansthatthemultiplicationoperatorhashigherprecedencethantheadditionoperator.

    ThefollowingtablegivestheprecedencetableforPython,fromthelowestprecedence(leastbinding)tothehighestprecedence(mostbinding).Thismeansthatinagivenexpression,Pythonwillfirstevaluatetheoperatorsandexpressionslowerinthetablebeforetheoneslistedhigherinthetable.

    Thefollowingtable,takenfromthePythonreferencemanual(http://docs.python.org/3/reference/expressions.html#operatorprecedence),isprovidedforthesakeofcompleteness.Itisfarbettertouseparenthesestogroupoperatorsandoperandsappropriatelyinordertoexplicitlyspecifytheprecedence.Thismakestheprogrammorereadable.SeeChangingtheOrderofEvaluationbelowfordetails.

    lambda

    LambdaExpression

    ifelse

    Conditionalexpression

    or

    BooleanOR

    and

    BooleanAND

    notx

    BooleanNOT

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

    Comparisons,includingmembershiptestsandidentitytests

    |

    BitwiseOR

    ^

    BitwiseXOR

    http://docs.python.org/3/reference/expressions.html#operator-precedence

  • 1/4/2015 AByteofPython

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

    &

    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.ChangingtheOrderOfEvaluationTomaketheexpressionsmorereadable,wecanuseparentheses.Forexample, 2+(3*4) isdefinitelyeasiertounderstandthan 2+3*4 whichrequiresknowledgeoftheoperatorprecedences.Aswitheverythingelse,theparenthesesshouldbeusedreasonably(donotoverdoit)andshouldnotberedundant,asin (2+(3*4)) .

    Thereisanadditionaladvantagetousingparenthesesithelpsustochangetheorderofevaluation.Forexample,ifyouwantadditiontobeevaluatedbeforemultiplicationinanexpression,thenyoucanwritesomethinglike (2+3)*4 .

  • 1/4/2015 AByteofPython

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

    8.5.AssociativityOperatorsareusuallyassociatedfromlefttoright.Thismeansthatoperatorswiththesameprecedenceareevaluatedinalefttorightmanner.Forexample, 2+3+4 isevaluatedas (23)+4 .Someoperatorslikeassignmentoperatorshaverighttoleftassociativityi.e. a=b=c istreatedas a=(b=c) .

    8.6.ExpressionsExample(saveasexpression.py):

    Output:

    HowItWorks

    Thelengthandbreadthoftherectanglearestoredinvariablesbythesamename.Weusethesetocalculatetheareaandperimeteroftherectanglewiththehelpofexpressions.Westoretheresultoftheexpression length*breadth inthevariableareaandthenprintitusingtheprintfunction.Inthesecondcase,wedirectlyusethevalueoftheexpression 2*(length+breadth) intheprintstatement.

    Also,noticehowPythonprettyprintstheoutput.Eventhoughwehavenotspecifiedaspacebetween'Areais' andthevariable area ,Pythonputsitforussothatwegetacleanniceoutputandtheprogramismuchmorereadablethisway(sincewedontneedtoworryaboutspacinginthestringsweuseforoutput).ThisisanexampleofhowPythonmakeslifeeasyfortheprogrammer.

    8.7.SummaryWehaveseenhowtouseoperators,operandsandexpressionsthesearethebasicbuildingblocksofanyprogram.Next,wewillseehowtomakeuseoftheseinourprogramsusingstatements.

    length=5breadth=2

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

    PYTHON

    $pythonexpression.pyAreais10Perimeteris14

  • 1/4/2015 AByteofPython

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

    9.ControlFlowIntheprogramswehaveseentillnow,therehasalwaysbeenaseriesofstatementsfaithfullyexecutedbyPythoninexacttopdownorder.Whatifyouwantedtochangetheflowofhowitworks?Forexample,youwanttheprogramtotakesomedecisionsanddodifferentthingsdependingondifferentsituations,suchasprinting'GoodMorning'or'GoodEvening'dependingonthetimeoftheday?

    Asyoumighthaveguessed,thisisachievedusingcontrolflowstatements.TherearethreecontrolflowstatementsinPythonif,forandwhile.

    9.1.TheifstatementTheifstatementisusedtocheckacondition:iftheconditionistrue,werunablockofstatements(calledtheifblock),elseweprocessanotherblockofstatements(calledtheelseblock).Theelseclauseisoptional.

    Example(saveasif.py):

    Output:

    number=23guess=int(raw_input('Enteraninteger:'))

    ifguess==number:#Newblockstartshereprint'Congratulations,youguessedit.'print'(butyoudonotwinanyprizes!)'#Newblockendshereelifguessnumbertoreachhere

    print'Done'#Thislaststatementisalwaysexecuted,#aftertheifstatementisexecuted.

    PYTHON

  • 1/4/2015 AByteofPython

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

    HowItWorks

    Inthisprogram,wetakeguessesfromtheuserandcheckifitisthenumberthatwehave.Wesetthevariablenumbertoanyintegerwewant,say 23 .Then,wetaketheusersguessusingtheraw_input() function.Functionsarejustreusablepiecesofprograms.Wellreadmoreabouttheminthenextchapter.

    Wesupplyastringtothebuiltin raw_input functionwhichprintsittothescreenandwaitsforinputfromtheuser.Onceweentersomethingandpress enter key,the raw_input() functionreturnswhatweentered,asastring.Wethenconvertthisstringtoanintegerusing int andthenstoreitinthevariable guess .Actually,the int isaclassbutallyouneedtoknowrightnowisthatyoucanuseittoconvertastringtoaninteger(assumingthestringcontainsavalidintegerinthetext).

    Next,wecomparetheguessoftheuserwiththenumberwehavechosen.Iftheyareequal,weprintasuccessmessage.NoticethatweuseindentationlevelstotellPythonwhichstatementsbelongtowhichblock.ThisiswhyindentationissoimportantinPython.Ihopeyouarestickingtothe"consistentindentation"rule.Areyou?

    Noticehowthe if statementcontainsacolonattheendweareindicatingtoPythonthatablockofstatementsfollows.

    Then,wecheckiftheguessislessthanthenumber,andifso,weinformtheuserthattheymustguessalittlehigherthanthat.Whatwehaveusedhereisthe elif clausewhichactuallycombinestworelatedifelseifelse statementsintoonecombined ifelifelse statement.Thismakestheprogrameasierandreducestheamountofindentationrequired.

    $pythonif.pyEnteraninteger:50No,itisalittlelowerthanthatDone

    $pythonif.pyEnteraninteger:22No,itisalittlehigherthanthatDone

    $pythonif.pyEnteraninteger:23Congratulations,youguessedit.(butyoudonotwinanyprizes!)Done

  • 1/4/2015 AByteofPython

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

    The elif and else statementsmustalsohaveacolonattheendofthelogicallinefollowedbytheircorrespondingblockofstatements(withproperindentation,ofcourse)

    Youcanhaveanother if statementinsidetheifblockofan if statementandsoonthisiscalledanested if statement.

    Rememberthatthe elif and else partsareoptional.Aminimalvalid if statementis:

    AfterPythonhasfinishedexecutingthecomplete if statementalongwiththeassociated elif andelse clauses,itmovesontothenextstatementintheblockcontainingthe if statement.Inthiscase,itisthemainblock(whereexecutionoftheprogramstarts),andthenextstatementisthe print'Done'statement.Afterthis,Pythonseestheendsoftheprogramandsimplyfinishesup.

    Eventhoughthisisaverysimpleprogram,Ihavebeenpointingoutalotofthingsthatyoushouldnotice.Alltheseareprettystraightforward(andsurprisinglysimpleforthoseofyoufromC/C++backgrounds).Youwillneedtobecomeawareofallthesethingsinitially,butaftersomepracticeyouwillbecomecomfortablewiththem,anditwillallfeel'natural'toyou.

    NOTENoteforC/C++Programmers

    Thereisno switch statementinPython.Youcanusean if..elif..elsestatementtodothesamething(andinsomecases,useadictionarytodoitquickly)

    9.2.ThewhileStatementThe while statementallowsyoutorepeatedlyexecuteablockofstatementsaslongasaconditionistrue.A while statementisanexampleofwhatiscalledaloopingstatement.A while statementcanhaveanoptional else clause.

    Example(saveas while.py ):

    ifTrue:print'Yes,itistrue'

    PYTHON

  • 1/4/2015 AByteofPython

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

    Output:

    HowItWorks

    Inthisprogram,wearestillplayingtheguessinggame,buttheadvantageisthattheuserisallowedtokeepguessinguntilheguessescorrectlythereisnoneedtorepeatedlyruntheprogramforeachguess,aswehavedoneintheprevioussection.Thisaptlydemonstratestheuseofthe while statement.

    Wemovethe raw_input and if statementstoinsidethe while loopandsetthevariable runningto True beforethewhileloop.First,wecheckifthevariable running is True andthenproceedtoexecutethecorrespondingwhileblock.Afterthisblockisexecuted,theconditionisagaincheckedwhichinthiscaseisthe running variable.Ifitistrue,weexecutethewhileblockagain,elsewecontinuetoexecutetheoptionalelseblockandthencontinuetothenextstatement.

    number=23running=True

    whilerunning:guess=int(raw_input('Enteraninteger:'))

    ifguess==number:print'Congratulations,youguessedit.'#thiscausesthewhilelooptostoprunning=Falseelifguess

  • 1/4/2015 AByteofPython

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

    The else blockisexecutedwhenthe while loopconditionbecomes False thismayevenbethefirsttimethattheconditionischecked.Ifthereisan else clausefora while loop,itisalwaysexecutedunlessyoubreakoutoftheloopwitha break statement.

    The True and False arecalledBooleantypesandyoucanconsiderthemtobeequivalenttothevalue1 and 0 respectively.

    NOTENoteforC/C++Programmers

    Rememberthatyoucanhavean else clauseforthe while loop.

    9.3.TheforloopThe for..in statementisanotherloopingstatementwhichiteratesoverasequenceofobjectsi.e.gothrougheachiteminasequence.Wewillseemoreaboutsequencesindetailinlaterchapters.Whatyouneedtoknowrightnowisthatasequenceisjustanorderedcollectionofitems.

    Example(saveas for.py ):

    Output:

    HowItWorks

    Inthisprogram,weareprintingasequenceofnumbers.Wegeneratethissequenceofnumbersusingthebuiltin range function.

    Whatwedohereissupplyittwonumbersand range returnsasequenceofnumbersstartingfromthefirstnumberanduptothesecondnumber.Forexample, range(1,5) givesthesequence [1,2,3,4] .Bydefault, range takesastepcountof1.Ifwesupplyathirdnumberto range ,thenthat

    foriinrange(1,5):printielse:print'Theforloopisover'

    PYTHON

    $pythonfor.py1234Theforloopisover

  • 1/4/2015 AByteofPython

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

    becomesthestepcount.Forexample, range(1,5,2) gives [1,3] .Rememberthattherangeextendsuptothesecondnumberi.e.itdoesnotincludethesecondnumber.

    Notethat range() generatesasequenceofnumbers,butitwillgenerateonlyonenumberatatime,whentheforlooprequestsforthenextitem.Ifyouwanttoseethefullsequenceofnumbersimmediately,use list(range()) .Listsareexplainedinthedatastructureschapter.

    The for looptheniteratesoverthisrange foriinrange(1,5) isequivalentto foriin[1,2,3,4] whichislikeassigningeachnumber(orobject)inthesequencetoi,oneatatime,andthenexecutingtheblockofstatementsforeachvalueof i .Inthiscase,wejustprintthevalueintheblockofstatements.

    Rememberthatthe else partisoptional.Whenincluded,itisalwaysexecutedonceafterthe for loopisoverunlessabreakstatementisencountered.

    Rememberthatthe for..in loopworksforanysequence.Here,wehavealistofnumbersgeneratedbythebuiltin range function,butingeneralwecanuseanykindofsequenceofanykindofobjects!Wewillexplorethisideaindetailinlaterchapters.

    NOTE

    NoteforC/C++/Java/C#Programmers

    ThePython for loopisradicallydifferentfromtheC/C++ for loop.C#programmerswillnotethatthe for loopinPythonissimilartothe foreach loopinC#.Javaprogrammerswillnotethatthesameissimilarto for(inti:IntArray) inJava1.5.

    InC/C,ifyouwanttowrite`for(inti=0i

  • 1/4/2015 AByteofPython

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

    Output:

    HowItWorks

    Inthisprogram,werepeatedlytaketheusersinputandprintthelengthofeachinputeachtime.Weareprovidingaspecialconditiontostoptheprogrambycheckingiftheuserinputis 'quit' .Westoptheprogrambybreakingoutoftheloopandreachtheendoftheprogram.

    Thelengthoftheinputstringcanbefoundoutusingthebuiltin len function.

    Rememberthatthe break statementcanbeusedwiththe for loopaswell.

    SwaroopsPoeticPythonTheinputIhaveusedhereisaminipoemIhavewritten:

    ProgrammingisfunWhentheworkisdoneifyouwannamakeyourworkalsofun:usePython!

    9.5.ThecontinueStatement

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

    PYTHON

    $pythonbreak.pyEntersomething:ProgrammingisfunLengthofthestringis18Entersomething:WhentheworkisdoneLengthofthestringis21Entersomething:ifyouwannamakeyourworkalsofun:Lengthofthestringis37Entersomething:usePython!Lengthofthestringis11Entersomething:quitDone

  • 1/4/2015 AByteofPython

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

    The continue statementisusedtotellPythontoskiptherestofthestatementsinthecurrentloopblockandtocontinuetothenextiterationoftheloop.

    Example(saveas continue.py ):

    Output:

    HowItWorks

    Inthisprogram,weacceptinputfromtheuser,butweprocesstheinputstringonlyifitisatleast3characterslong.So,weusethebuiltin len functiontogetthelengthandifthelengthislessthan3,weskiptherestofthestatementsintheblockbyusingthe continue statement.Otherwise,therestofthestatementsintheloopareexecuted,doinganykindofprocessingwewanttodohere.

    Notethatthe continue statementworkswiththe for loopaswell.

    9.6.SummaryWehaveseenhowtousethethreecontrolflowstatements if , while and for alongwiththeirassociated break and continue statements.ThesearesomeofthemostcommonlyusedpartsofPythonandhence,becomingcomfortablewiththemisessential.

    Next,wewillseehowtocreateandusefunctions.

    whileTrue:s=raw_input('Entersomething:')ifs=='quit':breakiflen(s)

  • 1/4/2015 AByteofPython

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

    10.FunctionsFunctionsarereusablepiecesofprograms.Theyallowyoutogiveanametoablockofstatements,allowingyoutorunthatblockusingthespecifiednameanywhereinyourprogramandanynumberoftimes.Thisisknownascallingthefunction.Wehavealreadyusedmanybuiltinfunctionssuchas lenand range .

    Thefunctionconceptisprobablythemostimportantbuildingblockofanynontrivialsoftware(inanyprogramminglanguage),sowewillexplorevariousaspectsoffunctionsinthischapter.

    Functionsaredefinedusingthe def keyword.Afterthiskeywordcomesanidentifiernameforthefunction,followedbyapairofparentheseswhichmayenclosesomenamesofvariables,andbythefinalcolonthatendstheline.Nextfollowstheblockofstatementsthatarepartofthisfunction.Anexamplewillshowthatthisisactuallyverysimple:

    Example(saveas function1.py ):

    Output:

    HowItWorks

    Wedefineafunctioncalled say_hello usingthesyntaxasexplainedabove.Thisfunctiontakesnoparametersandhencetherearenovariablesdeclaredintheparentheses.Parameterstofunctionsarejustinputtothefunctionsothatwecanpassindifferentvaluestoitandgetbackcorrespondingresults.

    Noticethatwecancallthesamefunctiontwicewhichmeanswedonothavetowritethesamecodeagain.

    10.1.FunctionParameters

    defsay_hello():#blockbelongingtothefunctionprint'helloworld'#Endoffunction

    say_hello()#callthefunctionsay_hello()#callthefunctionagain

    PYTHON

    $pythonfunction1.pyhelloworldhelloworld

  • 1/4/2015 AByteofPython

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

    Afunctioncantakeparameters,whicharevaluesyousupplytothefunctionsothatthefunctioncandosomethingutilisingthosevalues.Theseparametersarejustlikevariablesexceptthatthevaluesofthesevariablesaredefinedwhenwecallthefunctionandarealreadyassignedvalueswhenthefunctionruns.

    Parametersarespecifiedwithinthepairofparenthesesinthefunctiondefinition,separatedbycommas.Whenwecallthefunction,wesupplythevaluesinthesameway.Notetheterminologyusedthenamesgiveninthefunctiondefinitionarecalledparameterswhereasthevaluesyousupplyinthefunctioncallarecalledarguments.

    Example(saveas function_param.py ):

    Output:

    HowItWorks

    Here,wedefineafunctioncalled print_max thatusestwoparameterscalled a and b .Wefindoutthegreaternumberusingasimple if..else statementandthenprintthebiggernumber.

    Thefirsttimewecallthefunction print_max ,wedirectlysupplythenumbersasarguments.Inthesecondcase,wecallthefunctionwithvariablesasarguments. print_max(x,y) causesthevalueofargument x tobeassignedtoparameter a andthevalueofargument y tobeassignedtoparameter b .TheprintMaxfunctionworksthesamewayinbothcases.

    defprint_max(a,b):ifa>b:printa,'ismaximum'elifa==b:printa,'isequalto',belse:printb,'ismaximum'

    #directlypassliteralvaluesprint_max(3,4)

    x=5y=7

    #passvariablesasargumentsprint_max(x,y)

    PYTHON

    $pythonfunction_param.py4ismaximum7ismaximum

  • 1/4/2015 AByteofPython

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

    10.2.LocalVariablesWhenyoudeclarevariablesinsideafunctiondefinition,theyarenotrelatedinanywaytoothervariableswiththesamenamesusedoutsidethefunctioni.e.variablenamesarelocaltothefunction.Thisiscalledthescopeofthevariable.Allvariableshavethescopeoftheblocktheyaredeclaredinstartingfromthepointofdefinitionofthename.

    Example(saveas function_local.py ):

    Output:

    HowItWorks

    Thefirsttimethatweprintthevalueofthenamexwiththefirstlineinthefunctionsbody,Pythonusesthevalueoftheparameterdeclaredinthemainblock,abovethefunctiondefinition.

    Next,weassignthevalue 2 to x .Thename x islocaltoourfunction.So,whenwechangethevalueof x inthefunction,the x definedinthemainblockremainsunaffected.

    Withthelast print statement,wedisplaythevalueof x asdefinedinthemainblock,therebyconfirmingthatitisactuallyunaffectedbythelocalassignmentwithinthepreviouslycalledfunction.

    10.3.TheglobalstatementIfyouwanttoassignavaluetoanamedefinedatthetopleveloftheprogram(i.e.notinsideanykindofscopesuchasfunctionsorclasses),thenyouhavetotellPythonthatthenameisnotlocal,butitisglobal.Wedothisusingthe global statement.Itisimpossibletoassignavaluetoavariabledefinedoutsideafunctionwithoutthe global statement.

    x=50

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

    func(x)print'xisstill',x

    PYTHON

    $pythonfunction_local.pyxis50Changedlocalxto2xisstill50

  • 1/4/2015 AByteofPython

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

    Youcanusethevaluesofsuchvariablesdefinedoutsidethefunction(assumingthereisnovariablewiththesamenamewithinthefunction).However,thisisnotencouragedandshouldbeavoidedsinceitbecomesuncleartothereaderoftheprogramastowherethatvariablesdefinitionis.Usingthe globalstatementmakesitamplyclearthatthevariableisdefinedinanoutermostblock.

    Example(saveas function_global.py ):

    Output:

    HowItWorks

    The global statementisusedtodeclarethat x isaglobalvariablehence,whenweassignavaluetox insidethefunction,thatchangeisreflectedwhenweusethevalueof x inthemainblock.

    Youcanspecifymorethanoneglobalvariableusingthesame global statemente.g. globalx,y,z .

    10.4.DefaultArgumentValuesForsomefunctions,youmaywanttomakesomeparametersoptionalandusedefaultvaluesincasetheuserdoesnotwanttoprovidevaluesforthem.Thisisdonewiththehelpofdefaultargumentvalues.Youcanspecifydefaultargumentvaluesforparametersbyappendingtotheparameternameinthefunctiondefinitiontheassignmentoperator( = )followedbythedefaultvalue.

    Notethatthedefaultargumentvalueshouldbeaconstant.Moreprecisely,thedefaultargumentvalueshouldbeimmutablethisisexplainedindetailinlaterchapters.Fornow,justrememberthis.

    x=50

    deffunc():globalx

    print'xis',xx=2print'Changedglobalxto',x

    func()print'Valueofxis',x

    PYTHON

    $pythonfunction_global.pyxis50Changedglobalxto2Valueofxis2

  • 1/4/2015 AByteofPython

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

    Example(saveas function_default.py ):

    Output:

    HowItWorks

    Thefunctionnamed say isusedtoprintastringasmanytimesasspecified.Ifwedontsupplyavalue,thenbydefault,thestringisprintedjustonce.Weachievethisbyspecifyingadefaultargumentvalueof1 totheparameter times .

    Inthefirstusageof say ,wesupplyonlythestringanditprintsthestringonce.Inthesecondusageofsay ,wesupplyboththestringandanargument 5 statingthatwewanttosaythestringmessage5times.

    CAUTION

    Onlythoseparameterswhichareattheendoftheparameterlistcanbegivendefaultargumentvaluesi.e.youcannothaveaparameterwithadefaultargumentvalueprecedingaparameterwithoutadefaultargumentvalueinthefunctionsparameterlist.

    Thisisbecausethevaluesareassignedtotheparametersbyposition.Forexample, deffunc(a,b=5) isvalid,but deffunc(a=5,b) isnotvalid.

    10.5.KeywordArgumentsIfyouhavesomefunctionswithmanyparametersandyouwanttospecifyonlysomeofthem,thenyoucangivevaluesforsuchparametersbynamingthemthisiscalledkeywordargumentsweusethename(keyword)insteadoftheposition(whichwehavebeenusingallalong)tospecifytheargumentstothefunction.

    defsay(message,times=1):printmessage*times

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

    PYTHON

    $pythonfunction_default.pyHelloWorldWorldWorldWorldWorld

  • 1/4/2015 AByteofPython

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

    Therearetwoadvantagesone,usingthefunctioniseasiersincewedonotneedtoworryabouttheorderofthearguments.Two,wecangivevaluestoonlythoseparameterstowhichwewantto,providedthattheotherparametershavedefaultargumentvalues.

    Example(saveas function_keyword.py ):

    Output:

    HowItWorks

    Thefunctionnamed func hasoneparameterwithoutadefaultargumentvalue,followedbytwoparameterswithdefaultargumentvalues.

    Inthefirstusage, func(3,7) ,theparameter a getsthevalue 3 ,theparameter b getsthevalue 7and c getsthedefaultvalueof 10 .

    Inthesecondusage func(25,c=24) ,thevariable a getsthevalueof25duetothepositionoftheargument.Then,theparameter c getsthevalueof 24 duetonamingi.e.keywordarguments.Thevariable b getsthedefaultvalueof 5 .

    Inthethirdusage func(c=50,a=100) ,weusekeywordargumentsforallspecifiedvalues.Noticethatwearespecifyingthevalueforparameter c beforethatfor a eventhough a isdefinedbefore c inthefunctiondefinition.

    10.6.VarArgsparametersSometimesyoumightwanttodefineafunctionthatcantakeanynumberofparameters,i.e.variablenumberofarguments,thiscanbeachievedbyusingthestars(saveas function_varargs.py ):

    deffunc(a,b=5,c=10):print'ais',a,'andbis',b,'andcis',c

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

    PYTHON

    $pythonfunction_keyword.pyais3andbis7andcis10ais25andbis5andcis24ais100andbis5andcis50

  • 1/4/2015 AByteofPython

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

    Output:

    HowItWorks

    Whenwedeclareastarredparametersuchas *param ,thenallthepositionalargumentsfromthatpointtilltheendarecollectedasatuplecalled'param'.

    Similarly,whenwedeclareadoublestarredparametersuchas **param ,thenallthekeywordargumentsfromthatpointtilltheendarecollectedasadictionarycalled'param'.

    Wewillexploretuplesanddictionariesinalaterchapter.

    10.7.ThereturnstatementThe return statementisusedtoreturnfromafunctioni.e.breakoutofthefunction.Wecanoptionallyreturnavaluefromthefunctionaswell.

    Example(saveas function_return.py ):

    Output:

    deftotal(initial=5,*numbers,**keywords):count=initialfornumberinnumbers:count+=numberforkeyinkeywords:count+=keywords[key]returncount

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

    PYTHON

    $pythonfunction_varargs.py166

    defmaximum(x,y):ifx>y:returnxelifx==y:return'Thenumbersareequal'else:returny

    printmaximum(2,3)

    PYTHON

  • 1/4/2015 AByteofPython

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

    HowItWorks

    The maximum functionreturnsthemaximumoftheparameters,inthiscasethenumbe