Real Python

Embed Size (px)

Citation preview

  • 8/10/2019 Real Python

    1/209

    An introduction to Python throughpractical examples

    Fletcher Heisler

    Copyright 2012 RealPython.comPython and the original Python logo are registered trademarks o the Python !ot"are #oundation$

    modiied and used %yRealPython.com"ith permission rom the #oundation.

    http://realpython.com/http://www.python.org/psf/http://www.python.org/psf/http://realpython.com/http://realpython.com/http://realpython.com/http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://realpython.com/http://www.python.org/psf/http://realpython.com/
  • 8/10/2019 Real Python

    2/209

    Real Python RealPython.com

    0) Introduction......................................50.1) Why Python?...........................................................50.2) Why this book?........................................................60.3) How to use this book................................................70.4) icense..................................................................!

    1) "ettin# $t%rted...................................&1.1) 'own(o%d Python.....................................................&1.2) *en I'+..............................................................&1.3) Write % Python scri*t..............................................101.4) $crew thin#s u*.....................................................12

    1.5) $tore % ,%ri%b(e.....................................................14

    Inter(ude- e%,e yourse( he(*u( notes......16

    2) /und%ent%(s- $trin#s %nd ethods........1!2.1) e%rn to s*e%k in Python..........................................1!2.2) ess %round with your words....................................1&

    2.3) se obects %nd ethods.........................................23ssi#nent 2.3- Pick %*%rt your users in*ut.................................26

    3) /und%ent%(s- Workin# with $trin#s.......273.1) i %nd %tch dierent obects................................273.2) $tre%(ine your *rint st%teents...............................2&3.3) /ind % strin# in % strin#............................................31

    ssi#nent 3.3- urn your user into % (33t h40r...........................33

    4) /und%ent%(s- /unctions %nd oo*s.......344.1) 'o uturistic %rithetic...........................................34

    ssi#nent 4.1- Peror c%(cu(%tions on user in*ut........................36

    4.2) 8re%te your own unctions........................................37ssi#nent 4.2- 8on,ert te*er%tures........................................40

    4.3) 9un in circ(es........................................................40ssi#nent 4.3- r%ck your in,estents.......................................44

    2

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    3/209

    Real Python RealPython.com

    Inter(ude- 'ebu# your code.....................46

    5) /und%ent%(s- 8ondition%( (o#ic............515.1) 8o*%re ,%(ues.....................................................515.2) dd soe (o#ic.......................................................535.3) 8ontro( the (ow o your *ro#r%...............................5!

    ssi#nent 5.3- /ind the %ctors o % nuber................................61

    5.4) :re%k out o the *%ttern..........................................625.5) 9eco,er ro errors................................................655.6) $iu(%te e,ents %nd c%(cu(%te *rob%bi(ities..................6!

    ssi#nent 5.6.1- $iu(%te %n e(ection.......................................70

    ssi#nent 5.6.2- $iu(%te % coin toss e*erient.........................71

    6) /und%ent%(s- ists %nd 'iction%ries......726.1) %ke %nd u*d%te (ists..............................................72

    ssi#nent 6.1- W% *oetic......................................................77

    6.2) %ke *er%nent (ists..............................................7!6.3) $tore re(%tionshi*s in diction%ries..............................!0

    7) /i(e In*ut %nd ut*ut.........................!67.1) 9e%d %nd write si*(e i(es.......................................!67.2) se ore co*(ic%ted o(der structures.......................&1

    ssi#nent 7.2- se *%ttern %tchin# to de(ete i(es......................&7

    7.3) 9e%d %nd write 8$; d%t%..........................................&!ssi#nent 7.3- 8re%te % hi#h scores (ist ro 8$; d%t%.................102

    Inter(ude- Inst%(( *%ck%#es.....................103

    !) Inter%ct with P'/ i(es......................107!.1) 9e%d %nd write P'/s..............................................107!.2) %ni*u(%te P'/ i(es..............................................111

    ssi#nent !.2- dd % co,er sheet to % P'/ i(e...........................115

    3

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    4/209

    Real Python RealPython.com

    &) $

  • 8/10/2019 Real Python

    5/209

    Real Python RealPython.com

    0) Introduction

    hether you&re ne" to programming or a proessional code monkey looking to

    di'e into a ne" language$ this %ook "ill teach you all o thepracticalPython

    that you need to get started on pro(ects on your o"n.)Real Pythonemphasi*es real+"orld programming techni,ues$ "hich are illustrated

    through interesting$ useul examples. -o matter "hat your ultimate goals may %e$ i you

    "ork "ith computer at all$ you "ill soon %e inding endless "ays to impro'e your lie %y

    automating tasks and sol'ing pro%lems through Python programs that you create.

    0.1 )hy Python/

    ython is open+source ree"are$ meaning you can do"nload it or ree and use it

    or any purpose. t also has a great support community that has %uilt a num%er o

    additional ree tools. -eed to "ork "ith P# documents in Python/ here&s a ree

    package or that. )ant to collect data rom "e%pages/ -o need to start rom scratch3

    P

    Python "as %uilt to %e easier to use than other programming languages. t&s usually much

    easier to read Python code and 45C6aster to "rite code in Python than in other

    languages.

    #or instance$ here&s some simple code "ritten in C$ another commonly used

    programming language7

    #include int main ()

    {

    printf ("Hello, world\n");

    }

    All the program does is print 6ello$ "orld on the screen. hat "as a lot o "ork to

    print one phrase3 6ere&s the same code in Python7

    print "Hello, world"

    5

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    6/209

    Real Python RealPython.com

    !imple$ right/ 8asy$ aster$ more reada%le.

    At the same time$ Python has all the unctionality o other languages and more. 9ou

    might %e surprised ho" many proessional products are %uilt on Python code7 :mail$

    :oogle 4aps$ 9ouu%e$ reddit$ !potiy$ turnta%le.m$ 9ahoo3 :roups$ and the list goes

    on; And i it&s po"erul enough or %oth -A!A and the -!A$ it&s good enough or us.

    0.2 )hy this %ook/

    here are tonso %ooks and tutorials out there or learning Python already.

    6o"e'er$ most o the resources out there generally ha'e t"o main pro%lems7

    1 hey aren&t practical.2 hey aren&t interesting.

    4ost %ooks are so preoccupied "ith co'ering everylast possi%le 'ariation o every

    command that it&s easy to get lost in the details. n the end$ most o them end up

    looking more like the Python documentation pages. his is great as reerence material$

    %ut it&s a horri%le "ay to learn a programming language. -ot only do you spend most oyour time learning things you&ll ne'er use$ %ut it isn't any fun!

    his %ook is %uilt on the

  • 8/10/2019 Real Python

    7/209

    Real Python RealPython.com

    out into more ad'anced territory on your o"n "ill %e a %ree*e.

    !o di'e in3 >earn to program in a "idely used$ ree language that can do more than you

    e'er thought "as possi%le.

    0. 6o" to use this %ook

    or the most part$ you should approach the topics in the irst hal o this %ook in

    the same order as they are presented. his is less true o the second hal$ "hich

    co'ers a num%er o mostly non+o'erlapping topics$ although the chapters are generally

    increasing in diiculty throughout. you are a more experienced programmer$ then youmay ind yoursel heading to"ard the %ack o the %ook right a"ay ? %ut don&t neglect

    getting a strong oundation in the %asics irst3

    #

    8ach chapter section is ollo"ed %y re'ie" exercises to help you make sure that you&'e

    mastered all the topics co'ered. here are also a num%er o assignments$ "hich are

    more in'ol'ed and usually re,uire you to tie together a num%er o dierent concepts

    rom pre'ious chapters. he practice iles that accompany this course also include

    solution scripts to the assignments as "ell as some o the trickier exercises ? %ut to getthe most out o them$ you should try your %est to sol'e the assignment pro%lems on your

    o"n %eore looking at the example solutions.

    you get stuck$ you can al"ays log in at RealPython.comand ask or help on the

    mem%ers& orumB it&s likely that someone else has already experienced the same

    diiculty that you&re encountering and might %e a%le to guide you along.

    his %ook does mo'e ,uickly$ ho"e'er$ so i you&re completely ne" to programming$ you

    may "ant to supplement the irst e" chapters "ith additional practice. highly

    recommend "orking through the %eginning Python lessons a'aila%le or ree at the

    Codecademysite whileyou make your "ay through the %eginning o this material as the

    %est "ay to make sure that you ha'e all the %asics do"n.

    #inally$ i you ha'e any ,uestions or eed%ack a%out the course$ you&re al"ays "elcome

    to contact medirectly.

    7

    http://realpython.com/http://realpython.com/http://www.codecademy.com/tracks/pythonmailto:[email protected]://realpython.com/http://www.codecademy.com/tracks/pythonmailto:[email protected]://realpython.com/
  • 8/10/2019 Real Python

    8/209

    Real Python RealPython.com

    0. >icense

    his e+%ook is copyrighted and licensed under a Creati'e Commons Attri%ution+-onCommercial+-oeri's .0 5nported >icense. his means that you are "elcome

    to share this %ook and use it or any non+commercial purposes so long as the entire %ook

    remains intact and unaltered. hat %eing said$ i you ha'e recei'ed this copy or ree

    and ha'e ound it helpul$ "ould 'ery much appreciate i you purchaseda copy o your

    o"n.

    he example Python scripts associated "ith this %ook should %e considered open

    content. his means that anyone is "elcome to use any portion o the code or anypurpose.

    8

    http://realpython.com/http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://www.realpython.com/e-book/http://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://creativecommons.org/licenses/by-nc-nd/3.0/deed.en_UShttp://www.realpython.com/e-book/http://realpython.com/
  • 8/10/2019 Real Python

    9/209

    Real Python RealPython.com

    1) "ettin# $t%rted

    1.1 o"nload Python

    eore "e can do anything$ you ha'e to do"nload Python. 8'en i you already ha'e

    Python on your computer$ make sure that you ha'e the correct 'ersion7 2.7.3is

    the 'ersion used in this %ook and %y most o the rest o the "orld.

    Dheres % newer ,ersion Python 3.3 but it c%nt run code th%t w%s cre%ted with*re,ious ,ersions o Python @inc(udin# % (ot o useu( %nd i*ort%nt *%ck%#esth%t h%,ent been u*d%ted). s % resu(t Python 3 sti(( h%snt c%u#ht on yet.

    $ince ost o the code you(( see e(sewhere wi(( be ro Python 2.7 you shou(d(e%rn th%t irst. he two ,ersions %re sti(( verysii(%r %nd it wi(( t%ke you ,ery (itt(etie to #et used to the inor ch%n#es in Python 3 %ter you,e %stered Python 2.

    A

    %c users-9ou already ha'e a 'ersion o Python installed %y deault$ %ut it&s not quite

    the sameas the standard installation. 9ou should still do"nload Python 2.E. as

    directed %elo". @ther"ise$ you might run into pro%lems later "hen trying to installsome additional unctionality in Python or running code that in'ol'es graphics "indo"s.

    inu users-9ou might already ha'e Python 2.E. installed %y deault. @pen your

    erminal application and type pthon !!ersion to ind out. you ha'e 2.E.1 or

    2.E.2$ you should go ahead and update to the latest 'ersion.

    you need to$ go to http7==""".python.org=do"nload=to do"nload Python 2.7.3oryour operating system and install the program.

    1.2 @pen >8

    e&ll %e using >8 FInteracti'e 'e'eopment +n'ironment to "rite our Python

    code. >8 is a simple editing program that comes automatically installed "ith)9

    http://realpython.com/http://python3wos.appspot.com/http://www.python.org/download/http://python3wos.appspot.com/http://www.python.org/download/http://realpython.com/
  • 8/10/2019 Real Python

    10/209

    Real Python RealPython.com

    Python on )indo"s and 4ac$ and it "ill make our li'es much easier "hile "e&re coding.

    9ou could "rite Python scripts in any program rom a %asic text editor to a 'ery complex

    de'elopment en'ironment Fand many proessional coders use moread'ancedsetups$

    %ut >8 is simple to use and "ill easily pro'ide all the unctionality "e need.

    Windows-:o to your start menu and click on >8 FPython :5 rom the Python

    2.E program older to open >8. 9ou can also type >8 into the search %ar.

    $ B-:o to your Applications older and click on >8 rom the Python 2.E older

    to start running >8. Alternati'ely$ you can type $%& F"ithout ,uotes into your

    erminal "indo" to launch >8.

    inu- recommend that you install >8 to ollo" along "ith this course. 9ou could useGimor 8macs$ %ut they "ill not ha'e the same %uilt+in de%ugging eatures. o install

    >8 "ith admin pri'ileges7

    @n 5%untu=e%ian$ type7 sudo apt!'et install idle

    @n #edora=Red 6at=R68>=Cent@!$ type7 sudo um install pthon!tools

    @n !5!8$ you can search or >8 'ia install sot"are through 9a!.

    @pening >8$ you "ill see a %rie description o Python$ ollo"ed %y a prompt7

    >>>

    )e&re ready to program3

    1. )rite a Python script

    he "indo" "e ha'e open at the moment is >8&s interactive windowB usually this

    "indo" "ill (ust sho" us results "hen "e run programs that "e&'e "ritten$ %ut "e

    can also enter Python code into this "indo" directly. :o ahead and try typing some

    %asic math into the interacti'e "indo" at the prompt ? "hen you hit enter$ it should

    e'aluate your calculation$ display the result and prompt you or more input7

    >>>

    *

    >>>

    10

    http://realpython.com/http://pydev.org/https://www.jetbrains.com/pycharm/http://www.activestate.com/komodo-idehttp://sontek.net/blog/detail/turning-vim-into-a-modern-python-idehttp://gabrielelanaro.github.com/emacs-for-python/http://pydev.org/https://www.jetbrains.com/pycharm/http://www.activestate.com/komodo-idehttp://sontek.net/blog/detail/turning-vim-into-a-modern-python-idehttp://gabrielelanaro.github.com/emacs-for-python/http://realpython.com/
  • 8/10/2019 Real Python

    11/209

    Real Python RealPython.com

    >et&s try out some actual code. he standard program to display 6ello$ "orld on the

    screen isjust that simple in Python. ell the interacti'e "indo" to print the phrase %y

    using the printcommand like so7>>> print "Hello, world"

    Hello, world

    >>>

    I you w%nt to #et to *re,ious (ines you,e ty*ed into the inter%cti,e windowwithout ty*in# the out %#%in or co*yin# %nd *%stin# you c%n use the *%ir oshortcut keys A>HP@or on % %c CR>HP). +%ch tie you hit A>HP I'+ wi(( i((

    in the *re,ious (ine o code or you. Cou c%n then ty*e A>H-@$ B- CR>H-) tocyc(e b%ck to the net ost recent (ine o code.

    A

    -ormally "e "ill "ant to run more than one line o code at a time and sa'e our "ork so

    that "e can return to it later. o do this$ "e need to create a ne" script.

    #rom the menu %ar$ choose #ile -e" )indo" to generate a %lank script. 9ou should

    rearrange this "indo" and your interacti'e results "indo" so that you can see them

    %oth at the same time.

    ype the same line o code as %eore$ %ut put it in your ne" script7print "Hello, world"

    I you ust co*y %nd *%ste ro the inter%cti,e window into the scri*t %kesure you ne,er inc(ude the DEEE F *%rt o the (ine. h%ts ust the window%skin# or your in*utG it isnt *%rt o the %ctu%( code.A

    n order to run this script$ "e need to sa'e it irst. Choose #ile !a'e As;$ name the

    ile helloI"orld.py F"ithout the ,uotation marks and sa'e it some"here you&ll %e

    a%le to ind it later. he .py extension lets >8 kno" that it&s a Python script.

    >otice th%tprint%nd "Hello, world"%**e%r in dierent co(ors to (et you

    know th%tprintis % co%nd %nd "Hello, world"is % strin# o ch%r%cters.

    I you s%,e the scri*t %s soethin# other th%n % D.pF i(e @or i you dont

    inc(ude the D.pF etension this co(orin# wi(( dis%**e%r %nd e,erythin# wi(( turn

    b(%ck (ettin# you know th%t the i(e is no (on#er reco#nied %s % Python scri*t.

    A

    -o" that the script has %een sa'ed$ all "e ha'e to do in order to run the program is to

    11

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    12/209

    Real Python RealPython.com

    select Run Run 4odule rom the script "indo" For hit #J$ and "e&ll see the result

    appear in the interacti'e results "indo" (ust like it did %eore7

    >>>

    Hello, world>>>

    o open and edit a program later on$ (ust open up >8 again and select #ile @pen;$

    then %ro"se to and select the script to open it in a ne" script "indo".

    inu users-Read this o'er'ie"irst Fespecially section 2.2.2 i you "ant to %e a%le to

    run Python scripts outside o the editor.

    Cou i#ht see soethin# (ike the o((owin# (ine in the inter%cti,e window whenyou run or re=run % scri*t-

    >>> ++++++++++++++++++++++++++ &-/ ++++++++++++++++++++++++++

    his is ust I'+s w%y o (ettin# you know th%t e,erythin# %ter this (ine is the resu(to the new scri*t th%t you %re ust %bout to run. therwise i you r%n one scri*t%ter %nother @or one scri*t again%ter itse() it i#ht not be c(e%r wh%t out*utbe(on#s to which run o which scri*t.

    A

    1. !cre" things up

    'ery%ody makes mistakes ? especially "hile programming. n case you ha'en&t

    made any mistakes yet$ let&s get a head start on that and mess something up on

    purpose to see "hat happens.

    85sing >8$ there are t"o main types o errors you&ll experience. he most common is a

    syntaxerror$ "hich usually means that you&'e typed something incorrectly.

    >et&s try changing the contents o the script to7

    print "Hello, world

    6ere "e&'e (ust remo'ed the ending ,uotation mark$ "hich is o course a mistake ? no"

    12

    http://realpython.com/http://docs.python.org/tutorial/interpreter.htmlhttp://docs.python.org/tutorial/interpreter.htmlhttp://realpython.com/
  • 8/10/2019 Real Python

    13/209

    Real Python RealPython.com

    Python "on&t %e a%le to tell "here the string o text ends. !a'e your script and try

    running it. )hat happens/

    ;9ou can&t run it3 >8 is smart enough to reali*e there&s an error in your code$ and it

    stops you rom e'en trying to run the %uggy program. n this case$ it says7 8@> "hile

    scanning string literal. 8@> stands or 8nd @ >ine$ meaning that Python got all the

    "ay to the end o the line and ne'er ound the end o your string o text.

    >8 e'en highlights the place "here the error occurred using a dierent color and

    mo'es your cursor to the location o the error. 6andy3

    he other sort o error that you&ll experience is the type that >8 can'tcatch or you

    until your code is already running. ry changing the code in your script to7print Hello, world

    -o" "e&'e entirely remo'ed the ,uotation marks rom the phrase. -otice ho" the text

    changes color "hen "e do that/ >8 is letting us kno" that this is no longer a string o

    text that "e "ill %e printing$ %ut something else. )hat is our code doing no"/ )ell$

    sa'e the script and try to run it;

    he interacti'e "indo" "ill pop up "ith ugly red text that looks something like this7

    >>>

    race0ac1 (most recent call last)2

    3ile "4path to our script5\hello world.p", line , in

    print Hello, world

    6ame&rror2 name 7Hello7 is not defined

    >>>

    !o "hat happened/ Python is telling us a e" things7

    An error occurred ? speciically$ Python calls it a 6ame&rror

    he error happened on line o the script

    he line that generated the error "as7 print Hello, world

    he speciic error "as7 name 7Hello7 is not defined

    his is called a run+timeerror since it only occurs once the programming is already

    running. !ince "e didn&t put ,uotes around Hello, world$ Python didn&t kno" that this

    13

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    14/209

    Real Python RealPython.com

    "as text "e "anted to print. nstead$ it thought "e "ere reerring to t"o 'aria%les that

    "e "anted to print. he irst 'aria%le it tried to print "as something named 6ello +

    %ut since "e hadn&t deined a 'aria%le named 6ello$ our program crashed.

    9e,iew eercises-

    )rite a script that >8 "on&t let you run %ecause it has a syntaxerror

    )rite a script that "ill only crash your program once it is already running

    %ecause it has a run-timeerror

    1.J !tore a 'aria%le

    >et&s try "riting a dierent 'ersion o the pre'ious script. 6ere "e&ll use a 'aria%le to

    store our text %eore printing the text to the screen7

    phrase + "Hello, world"

    print phrase

    -otice the dierence in "here the ,uotation marks go rom our pre'ious script. )e arecreating a 'aria%le named phraseand assigning it the 'alue o the string o text

    "Hello, world". )e then print the phrase to the screen. ry sa'ing this script and

    running these t"o linesB you should see the same output as %eore7

    >>>

    Hello, world

    >>>

    -otice that in our script "e didn&t say7print "phrase"

    5sing ,uotes here "ould (ust print the "ord phrase instead o printing the contents o

    the 'aria%le named phrase.

    Phr%ses th%t %**e%r in uot%tion %rks %re c%((ed strings. We c%(( the strin#sbec%use theyre ust th%t J strin#s o ch%r%cters. strin# is one o the ost b%sicbui(din# b(ocks o %ny *ro#r%in# (%n#u%#e %nd we(( use strin#s % (ot o,er the

    net ew ch%*ters.

    A14

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    15/209

    Real Python RealPython.com

    )e also didn&t type our code like this7

    8hrase + "Hello, world"

    print phrase

    Can you spot the dierence/ n this example$ the irst line deines the 'aria%le 8hrase

    "ith a capital P at the %eginning$ %ut the second line prints out the 'aria%le phrase.

    $ince Python is c%se=sensiti,e the ,%ri%b(es 8hrase%nd phrase%re entire(y

    dierent thin#s. ikewise co%nds st%rt with (owerc%se (ettersG we c%n te((Python to print but it wou(dnt know how to 8rint. Kee* this i*ort%nt

    distinction in indA

    A)hen you run into trou%le "ith the sample code$ %e sure to dou%le+check that e'ery

    character in your code Foten including spaces exactly matches the examples.

    Computers don&t ha'e any common sense to interpret "hat you meantto say$ so %eing

    almost correct still "on&t get a computer to do the right thing3

    9e,iew eercises-

    5sing the interacti'e "indo"$ display some text on the screen %y using print

    5sing the interacti'e "indo"$ display a string o text %y sa'ing the string to a

    'aria%le$ then printing the contents o that 'aria%le

    o each o the irst t"o exercises again %y irst sa'ing your code in a script

    and then running the script

    15

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    16/209

    Real Python RealPython.com

    Interlude- e%,e yourse( he(*u( notes

    s you start to "rite more complicated scripts$ you&ll start to ind yoursel going

    %ack to parts o your code ater you&'e "ritten them and thinking$ "hat the heck

    "as that supposed to do/Ao a'oid these moments$ you can lea'e yoursel notes in your codeB they don&t aect the

    "ay the script runs at all$ %ut they help to document "hat&s supposed to %e happening.

    hese notes are reerred to as comments$ and in Python you start a comment "ith a

    pound F# sign.

    1

    @ur irst script could ha'e looked like this7# his is m first script9

    phrase + "Hello, world."

    print phrase # this line displas "Hello, world"

    he irst line doesn&t do anything$ %ecause it starts "ith a #. his tells Python to ignore

    the line completely %ecause it&s (ust a note or you.

    >ike"ise$ Python ignores the comment on the last lineB it "ill still print phrase$ %ut

    e'erything starting "ith the #is simply a comment.

    @ course$ you can still use a K sym%ol inside o a string. #or instance$ Python "on&t

    mistake the ollo"ing or the start o a comment7

    print "#"

    you ha'e a lot to say$ you can also create comments that span o'er multiple lines %y

    using a series o three single ,uotes F777 or three dou%le ,uotes F""" "ithout any

    spaces %et"een them. @nce you do that$ everythingater the 777or """%ecomes a

    comment until you closethe comment "ith a matching 777or """. #or instance$ i you

    "ere eeling excessi'ely 'er%ose$ our irst script could ha'e looked like this7

    777 his is m first script.

    t prints the phrase "Hello, world."

    he comments are lon'er than the script9 777

    phrase + "Hello, world."

    print phrase""" he line a0oe displas "Hello, world" """

    1 he #sym%ol is alternately reerred to as a num%er sign$ a hash$ a crosshatch$ or an octothorp. Really.

    16

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    17/209

    Real Python RealPython.com

    he irst three lines are no" all one comment$ since they all %et"een pairs o 777. 9ou

    can&t add a multi+line comment at the end o a line o code like "ith the K 'ersion$

    "hich is "hy the last comment is on its o"n separate line. F)e&ll see "hy in the nextchapter.

    Desides lea'ing yoursel notes$ another common use o comments is to comment out

    code "hile you&re testing parts o a scripts to temporarily stop that part o the code

    rom running. n other "ords$ adding a K at the %eginning o a line o code is an easy

    "ay to make sure that you don&t actually use that line$ e'en though you might "ant to

    keep it and use it later.

    17

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    18/209

    Real Python RealPython.com

    2) /und%ent%(s- $trin#s %nd ethods

    2.1 >earn to speak in Python

    s "e&'e already seen$ you "rite strings in Python %y surrounding them "ith ,uotes.

    9ou can use single ,uotes or dou%le ,uotes$ as long as you&re consistent or any

    one string. All o the ollo"ing lines create string 'aria%les Fcalled string literals%ecause

    "e&'e literally "ritten out exactly ho" they look7

    A

    phrase + 7Hello, world.7

    m-trin' + ":e7re #9"

    strin'6um0er + "*"

    conersation + 7 said, "8ut it oer 0 the llama."7

    !trings can include anycharacters + letters$ num%ers and sym%ols. 9ou can see the

    %eneit o using either single or dou%le ,uotes in the last string exampleB since "e used

    single ,uotes$ "e didn&t ha'e any trou%le putting dou%le ,uotes insidethe string. Fhere

    are other "ays to do this$ %ut "e&ll get to those later in the chapter.

    )e can also create really long strings that take up multiple lines %y using three single

    ,uotes For three dou%le ,uotes$ like this7

    lon'-trin' + 777his is a

    strin' that spans across multiple lines777

    lon'-trin' + """his is a new strin'

    that spans across two lines"""

    6ere "e assigned one 'alue to the 'aria%le lon'-trin'$ then "e o'er"rote that 'alue"ith a ne" string literal. ry putting this in a script and then printthe 'aria%le

    lon'-trin'B you&ll see that it displays the string on t"o separate lines. 9ou can also

    see no" "hy you can&t ha'e multi+line comments appear on the same line as actual

    codeB Python "ouldn&t %e a%le to tell the dierence %et"een these and actual string

    'aria%les3

    @ne last thing a%out strings7 i you "ant to "rite out a really long string$ %ut you don't

    18

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    19/209

    Real Python RealPython.com

    "ant it to appear on multiple lines$ you can use a %ackslash like this "hen "riting it out7

    m%on'-trin' + "Here7s a strin' that want to write \

    across multiple lines since it is lon'."

    -ormally Python "ould get to the end o the irst line and get angry "ith you %ecause

    you hadn&t closed the string "ith a matching single ,uote. Dut %ecause there&s a

    %ackslash at the end$ you can (ust keep "riting the same string on the next line. his is

    dierent rom the last example since the actual string isn&t stored on multiple lines this

    time$ thereore the string gets displayed on a single line "ithout the %reak7

    >>> print m%on'-trin'

    Here7s a strin' that want to write across multiple lines since it is lon'.

    >>>

    s we,e %(re%dy discussed Python is c%se=sensiti,e. :y con,ention Pythonsbui(t=in unctions %nd ethods use ec(usi,e(y (ower=c%se. $ince % sin#(e,%ri%b(e n%e c%nt inc(ude %ny s*%ces or d%shes when *ro#r%ers w%nt to

    #i,e descri*ti,e n%es to ,%ri%b(es one w%y o %kin# the e%si(y re%d%b(e is touse [email protected]. m%on'-trin') so c%((ed bec%use o the u**er=c%se Dhu*sF

    in the idd(e o ters. We(( ost(y stick to c%e(8%se in this course but %nother*o*u(%r ethod is to se*%r%te words usin# underscores @i.e. m=lon'=strin').

    A

    9e,iew eercises-

    printa string that uses dou%le ,uotation marks insidethe string

    printa string that uses an apostrophe Fsingle ,uote insidethe string

    printa string that spans across multiple lines

    printa one+line string that you ha'e "ritten out on multiple lines

    2.2 4ess around "ith your "ords

    ython has some %uilt+in unctionality that "e can use to modiy our strings or get

    more inormation a%out them. #or instance$ there&s a length unctionP19

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    20/209

    Real Python RealPython.com

    Fa%%re'iated as len in Python that can tell you the length o all sorts o things$

    including strings. ry typing these lines into the interacti'e "indo"7

    >>> m-trin' + "a0c"

    >>> len'thf-trin' + len(m-trin')>>> print len'thf-trin'

    >>>

    #irst "e created a string named m-trin'. hen "e used the len()unction on

    m-trin'to calculate its length$ "hich "e store in the ne" 'aria%le "e named

    len'thf-trin'. )e ha'e to gi'e the len()unction some inputor its calculation$

    "hich "e do %y placing m-trin'ater it in the parentheses ? you&ll see more on

    exactly ho" this "orks later. he length o 7a0c7is (ust the total num%er o characters

    in it$ $ "hich "e then printto the screen.

    )e can com%ine strings together as "ell7

    >>> strin' + "a0ra"

    >>> strin'* + "cada0ra"

    >>> ma'ic-trin' + strin' strin'*

    >>> print ma'ic-trin'

    a0racada0ra

    >>>

    @r e'en like this$ "ithout creating any ne" 'aria%les7

    >>> print "a0ra" "ca" "da0ra"

    a0racada0ra

    >>>

    n programming$ "hen "e add strings together like this$ "e say that "e concatenate

    them.

    Cou(( see % (ot o it%(icied ters throu#hout the irst ew ch%*ters o this book.'ont worry %bout eoriin# %(( o the i theyre un%i(i%rA Cou dont need%ny %ncy %r#on to *ro#r% we(( but its #ood to be %w%re o the correct

    terino(o#y. Pro#r%ers tend to throw %round technic%( ters % (otG not on(y doesit %((ow or ore *recise counic%tion but it he(*s %ke si*(e conce*ts soundore i*ressi,e.

    A

    )hen "e "ant to com%ine many strings at once$ "e can also use commas to separate

    them. his "ill automatically add spaces %et"een the strings$ like so7

    20

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    21/209

    Real Python RealPython.com

    >>> print "a0ra", "ca", "da0ra"

    a0ra ca da0ra

    >>>

    @ course$ the commas ha'e to go outsideo the ,uotation marks$ since other"ise thecommas "ould %ecome part o the actual strings themsel'es.

    !ince a string is (ust a se,uence o characters$ "e should %e a%le to access each

    character indi'idually as "ell. )e can do this %y using s,uare %rackets ater the string$

    like this7

    >>> flaor + "0irthda ca1e"

    >>> print flaor45

    t

    >>>

    )ait$ %ut t is the ourth character3 )ell$ not in the programming "orld; n Python

    Fand most other programming languages$ we st%rt countin# %t 0. !o in this case$ % is

    the *eroth character o the string 0irthda ca1e. his makes i thefirst

    character$ r the second$ and t the third.

    "e "anted to display "hat "e "ould normally tend to think o as the irst

    character$ "e "ould actually need to print the 0 thcharacter7

    >>> print flaor4?5

    0

    >>>

    :e c%reu( when youre usin#-= *%rentheses- ()

    = su%re br%ckets- []

    = cur(y br%ces- {}

    hese alle%n dierent thin#s to Python so you c%n ne,er switch one or %nother.

    We(( see ore e%*(es o when e%ch one is used @%nd we h%,ent seen {}yet)but kee* in ind th%t theyre %(( used dierent(y.

    A

    he num%er that "e assigned to each character&s position is called the indexor subscript

    num%er$ and Python thinks o the string like this7

    @haracter2 b i r t h d ...

    ndeA B -u0script #2 ? * C ...

    21

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    22/209

    Real Python RealPython.com

    )e can get a particular section out o the string as "ell$ %y using s,uare %rackets and

    speciying the rangeo characters that "e "ant. )e do this %y putting a colon %et"een

    the t"o su%script num%ers$ like so7

    >>> flaor + "0irthda ca1e"

    >>> print flaor4?25

    0ir

    >>>

    6ere "e told Python to sho" us only the irst three characters o our string$ starting at

    the 0thcharacter and going up untilF%ut not including the rdcharacter. he num%er

    %eore the colon tells Python the irst character "e "ant to include$ "hile the num%er

    ater the colon says that "e "ant to stopjust beforethat character.

    "e use the colon in the %rackets %ut omit one o the num%ers in a range$ Python "ill

    assume that "e meant to go all the "ay to the end o the string in that direction7

    >>> flaor + "0irthda ca1e"

    >>> print flaor42C5

    0irth

    >>> print flaor4C25

    da ca1e

    >>> print flaor425

    0irthda ca1e>>>

    he "ay "e&re using %rackets ater the string is reerred to as subscriptingor indexing

    since it uses the index num%ers o the string&s characters.

    Python strin#s %re immutable e%nin# th%t they c%nt be ch%n#ed once you,ecre%ted the. /or inst%nce see wh%t h%**ens when you try to %ssi#n % new(etter to one *%rticu(%r ch%r%cter o % strin#-

    m-trin' + "'oal"

    m-trin'4?5 + "f" # this won7t wor19

    Inste%d we wou(d h%,e to cre%te %n entire(y new strin# @%(thou#h we c%n sti(( #i,em-trin'th%t new,%(ue)- m-trin' + "'oal" m-trin' + "f" m-trin'425

    In the irst e%*(e we were tryin# to ch%n#eparto m-trin'%nd kee* the rest

    o it unch%n#ed which doesnt work. In the second e%*(e we cre%ted % newstrin# by %ddin# two strin#s to#ether one o which w%s % *%rt o m-trin'G thenwe

    took th%t newstrin# %nd co*(ete(y re%ssi#ned m-trin'to this new ,%(ue.

    A

    22

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    23/209

    Real Python RealPython.com

    9e,iew eercises-

    Create a string and printits length using the len()unction

    Create t"o strings$ concatenate them Fadd them next to each other and

    printthe com%ination o the t"o strings

    Create t"o string 'aria%les$ then printone o them ater the other F"ith a

    space added in %et"een using a comma in your printstatement

    printthe string Din' %y using su%scripting and index num%ers on the

    string 0aDin'a to speciy the correct range o characters

    2. 5se o%(ects and methods

    he Python programming language is an example o Object-Oriented Programming

    FOOP$ "hich means that "e store our inormation in objects. n Python$ a stringis an example o an o%(ect.2!trings are 'ery simple o%(ects + they only hold one piece o

    inormation Ftheir 'alue ? %ut a single o%(ect can %e 'ery complex. @%(ects can e'en

    hold other o%(ects inside o them. his helps to gi'e structure and organi*ation to our

    programming.

    #or instance$ i "e "anted to model a car$ "e "ould Fhypothetically create a Car o%(ect

    that holds lots o descripti'e inormation a%out the car$ called its attributes. t "ould

    ha'e a color attri%ute$ a model attri%ute$ etc.$ and each o these attri%utes "ould hold

    one piece o descripti'e inormation a%out the car. t "ould also include dierent

    o%(ects like ires$ oors$ and an 8ngine that all ha'e their o"n attri%utes as "ell.

    ierent o%(ects also ha'e dierent capa%ilities$ called methods. #or instance$ our Car

    o%(ect might ha'e a drie()method and a par1()method. !ince these methods

    belongto the car$ "e use them "ith dot notation %y putting them next to the o%(ect

    2 !trings are actually called stro%(ects in Python$ %ecause programmers are la*y and don&t "ant to type

    more than is a%solutely necessary. Dut you&ll al"ays hear string o%(ects reerred to as (ust strings.

    23

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    24/209

    Real Python RealPython.com

    and ater a period$ like this7

    car.par1()

    4ethods are ollo"ed %y parentheses$ %ecause sometimes methods use input. #orinstance$ i "e "anted to dri'e the car o%(ect a distance o J0$ "e "ould place that

    input o J0 in the parentheses o the dri'e method7

    car.drie(C?)

    here are certain methods that %elong to string o%(ects as "ell. #or instance$ there is a

    string method called upper()that creates an upper+case 'ersion o the string.

    F>ike"ise$ there is a corresponding method lower()that creates a lo"er+case 'ersion

    o a string. >et&s gi'e it a try in the interacti'e "indo"7

    >>> loudEoice + "@an ou hear me etF"

    >>> print loudEoice.upper()

    @/6 G H&/ I& G&F

    >>>

    )e created a string loudEoice$ then "e called its upper()method to return the

    upper+case 'ersion o the string$ "hich "e printto the screen.

    ethods %re ust unctions th%t belongto obects. We %(re%dy s%w %n e%*(eo % #ener%(=*ur*ose unction the len()unction which c%n be used to te(( us

    the (en#th o %ny differentty*es o obects inc(udin# strin#s. his is why weuse the (en#th unction dierent(y by on(y s%yin#-

    len(loudEoice)

    e%nwhi(e we use dot not%tion to c%(( ethods th%t belong to %n obect (ike whenwe c%(( the upper()ethod th%t be(on#s to the strin# loudEoice-

    loudEoice.upper()

    A

    >et&s make things more interacti'e %y introducing one more general unction. )e&re

    going to get some input rom the user o our program %y using the unction

    raw=input(). he input that "e pass to this unction is the text that "e "ant it to

    display as a promptB "hat the unction actually doesis to recei'e additional input rom

    the user. ry running the ollo"ing script7

    24

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    25/209

    Real Python RealPython.com

    usernput + raw=input("He, what7s upF ")

    print "Gou said2", usernput

    )hen you run this$ instead o the program ending and taking you %ack to the >>>

    prompt$ you&ll (ust see7

    >>>He, what7s upF

    ..."ith a %linking cursor. t&s "aiting or you to ans"er38nter a response$ and it "ill

    store that ans"er in the usernputstring and display it %ack7

    >>>He, what7s upF Iind our own 0usiness.Gou said2 Iind our own 0usiness.

    >>>

    -o" "e&ll com%ine the unction raw=input()"ith the string method upper()in a

    script to modiy the user&s input7

    response + raw=input(":hat should shoutF ")

    response + response.upper()

    print ":ell, if ou insist...", response

    Calling response.upper()didn&t change anything a%out our responsestring. he

    upper()method only returnedthe upper+case 'ersion o the string to us$ and it "as up

    to us to do something "ith it. hat&s "hy "e had to set response +

    response.upper()in order to reassignthe 'alue o the string responseto its o"n

    upper+case e,ui'alent.

    In I'+ i you w%nt to see %(( the ethods c%n %**(y to % *%rticu(%r kind oobect you c%n ty*e th%t obect out o((owed by % *eriod %nd then hitCR>H!PAC8. /or inst%nce irst deine % strin# obect in the inter%cti,e window-

    >>> m-trin' + "1erfuffle"

    >ow ty*e the n%e o your strin# in %#%in o((owed by % *eriod @without hittin#enter)- >>> m-trin'.

    When you hit CR>H!PAC8 you(( see % (ist o ethod o*tions th%t you c%n scro((throu#h with the %rrow keys. $trin#s h%,e (ots o ethodsA

    A

    -otice that "e added a space at the end o the string "e supplied to raw=input(). his isn&t

    mandatory$ %ut that "ay the user&s input doesn&t sho" up on the screen rightnext to our prompt.

    25

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    26/209

    Real Python RealPython.com

    re(%ted shortcut in I'+ is the %bi(ity to i(( in tet %uto%tic%((y without h%,in# toty*e in (on# n%es by hittin# /J. /or inst%nce i you on(y ty*e in Dm-trin'.uF

    %nd then hit the /Jkey I'+ wi(( %uto%tic%((y i(( in Dm-trin'.upperF bec%use

    there is on(y one ethod be(on#in# to m-trin'th%t be#ins with % DuF. In %ct this

    e,en works with ,%ri%b(e n%esG try ty*in# in ust the irst ew (etters oDm-trin'F %nd %ssuin# you dont h%,e %ny other n%es %(re%dy deined th%t

    sh%re those irst (etters I'+ wi(( %uto%tic%((y co*(ete the n%e Dm-trin'F or

    you when you hit the /Jkey.

    9e,iew eercises-

    )rite a script that takes input rom the user and displays that input %ack

    5se CR>H!PAC8 to 'ie" all the methods o a string o%(ect$ then "rite a

    script that returns the lo"er+case 'ersion o a string

    Assignment 2.3: Pick apart your user's input

    Write % scri*t n%ed DirstL(etter.*yF th%t irst *ro*ts the user or in*ut byusin# the strin#-

    ell me our password2

    he scri*t shou(d then deterine the irst (etter o the users in*ut con,ert th%t(etter to u**er=c%se %nd dis*(%y it b%ck. s %n e%*(e i the user in*ut w%s DnoF

    then the *ro#r% shou(d res*ond (ike this-

    he first letter ou entered was2 6

    /or now its ok%y i your *ro#r% cr%shes when the user enters nothin# %s in*ut@ust hittin# 8-8Rinste%d). We(( ind out % cou*(e w%ys you cou(d de%( with thissitu%tion in ch%*ter 5.

    ?

    26

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    27/209

    Real Python RealPython.com

    3) /und%ent%(s- Workin# with $trin#s

    .1 4ix and match dierent o%(ects

    e&'e seen that string o%(ects can hold any characters$ including num%ers.

    6o"e'er$ don&t conuse string num%ers "ith actual num%ers3 #or instance$ try

    this %it o code out in the interacti'e "indo"7

    )>>> m6um0er + "*"

    >>> print m6um0er m6um0er**

    >>>

    )e can add strings together$ %ut "e&re (ust concatenatingthem ? "e&re not actually

    adding the t"o ,uantities together. Python "ill e'en let us multiply strings as "ell7

    >>> m6um0er + "*"

    >>> print m6um0er K

    ***

    >>>

    "e "ant to change a string o%(ect into a num%er$ there are t"o general unctions "e

    commonly use7 int()and float().

    int()stands or integer and con'erts o%(ects into "hole num%ers$ "hile loat()

    stands or loating+point num%er and con'erts o%(ects into num%ers that ha'e decimal

    points. #or instance$ "e could change the string m6um0erinto an integer or a loat

    like so7

    >>> m6um0er + "*"

    >>> print int(m6um0er)

    *

    >>> print float(m6um0er)

    *.?

    >>>

    -otice ho" the second 'ersion added a decimal point$ %ecause the loating+point

    num%er has moreprecisionFmore decimal places. #or this reason$ "e couldn&t change a

    27

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    28/209

    Real Python RealPython.com

    string that looks like a loating+point num%er into an integer %ecause "e "ould ha'e to

    lose e'erything ater the decimal7

    >>> m6um0er + "*.?"

    >>> print int(m6um0er)

    race0ac1 (most recent call last)2

    3ile "", line , in

    print int(m6um0er)

    Ealue&rror2 inalid literal for int() with 0ase ?2 7*.?7

    >>>

    8'en though the extra 0 ater the decimal place doesn&t actually add any 'alue to our

    num%er$ Python is telling us that "e can&t (ust change 12.0 into 12 ? %ecause "e might

    lose part o the num%er.

    you "ant to turn a num%er into a string$ o course there&s a unction or that$ too ? the

    str()unction. @ne place "here this %ecomes important to do is "hen "e "ant to add

    string and num%ers together. #or instance$ "e can&t (ust concatenate the t"o dierent

    types o o%(ects like this7

    >>> print ""

    race0ac1 (most recent call last)2 3ile "", line , in

    print ""

    pe&rror2 cannot concatenate 7str7 and 7int7 o0Lects

    >>>

    Python doesn&t kno" ho" to add dierent types o o%(ects together ? "e could ha'e

    meant the ans"er to %e 2 or 11 depending on "hether "e had strings or integers.

    "e "anted to put the t"o num%ers side+%y+side as one string$ "e "ould ha'e to convert

    the integer into a string7>>> print "" str()

    >>>

    nteger and string are called typeso o%(ects. Al"ays keep in mind that you might

    get unexpected results i you mix types incorrectly or i you use one type o o%(ect "hen

    you really meant to use another.

    28

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    29/209

    Real Python RealPython.com

    9e,iew eercises-

    Create a string o%(ect that stores an integer as its 'alue$ then con'ert that

    string into an actualinteger o%(ect using int()B test that your ne" o%(ect isreally a num%er %y multiplying it %y another num%er and displaying the result

    Repeat the pre'ious exercise$ %ut use a loating+point num%er and float()

    Create a string o%(ect and an integer o%(ect$ then display them side+%y+side

    "ith a single printstatement %y using the str()unction

    .2 !treamline your printstatements

    uppose "e ha'e a string o%(ect$ name + "Maphod"$ and t"o integer o%(ects$

    numHeads + *and num/rms + . )e "ant to display them in the ollo"ing line7!Maphod has * heads and arms

    )e&'e already seen t"o "ays o doing this. he irst "ould in'ol'e using commas toinsert spaces %et"een each piece o our statement7

    print name, "has", str(numHeads), "heads and", str(num/rms), "arms"

    Another "ay "e could do this is %y concatenating the strings "ith the operator7

    print name" has "str(numHeads)" heads and "str(num/rms)" arms"

    didn&t use spaces around all the signs (ust so that the t"o expressions "ould line up$

    %ut it&s pretty diicult to read either "ay. rying to keep track o "hat goes inside oroutside o the ,uotes can %e a huge pain$ "hich is "hy there&s a third "ay o com%ining

    strings together7 using the string format()method.

    he simplest 'ersion o the format()method "ould look like this or our example7

    print "{} has {} heads and {} arms".format(name, numHeads, num/rms)

    he pairs o empty curly %races F{}"ithout any space in %et"een the t"o ser'e as

    29

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    30/209

    Real Python RealPython.com

    place+holders or the 'aria%les that "e "ant to place inside the string. )e then pass

    these 'aria%les into our string as inputs o the string&s format()method$ in order. he

    really great part a%out this techni,ue is that "e didn&t e'en ha'e to change our integers

    into string types irst ? the format()method did that or us automatically.

    Although it&s less re,uently used$ "e can also use index num%ers inside the curly %races

    to do the same thing7

    print "{?} has {} heads and {*} arms".format(name, numHeads, num/rms)

    6ere "e&'e inserted nameinto the {?}place+holder %ecause it is the 0thinput listed$

    and so on. !ince "e num%ered our place+holders$ "e don&t e'en ha'e to pro'ide the

    inputs in the same order. #or instance$ this line "ould also do the exact same thing7

    print "{*} has {} heads and {?} arms".format(num/rms, numHeads, name)

    his style o ormatting can %e helpul i you "ant to repeat an input multiple times

    "ithin a string$ i.e.7

    >>> print "{?} has {?} heads and {?} arms".format(name)Maphod has Maphod heads and Maphod arms.

    >>>

    #inally$ i "e didn&t "ant to create three separate o%(ects ahead o time$ one last "ay o

    using format()"ould %e to name andassign ne" o%(ects inside the format()

    method$ like so7

    print "{name} has {numHeads} heads and {num/rms} arms".format(name+"Maphod",numHeads+*, num/rms+)

    hese input 'aria%les don&t necessarily ha'e to %e listed in the same order since "e&'e

    called on each o them %y name inside the string.

    here is %(so %nother w%y to printor%tted strin#s- usin# the No*er%tor. Cou

    i#ht see this in code th%t you ind e(sewhere %nd you c%n re%d %bout how itworks herei youre curious but ust be %w%re th%t this sty(e is bein# *h%sed

    out co*(ete(y in Python 3 @%nd the DnewF format()sty(e works ust ine in

    Python 2.7) so theres not uch *oint in (e%rnin# to %ster this outd%ted ethod.

    A

    9e,iew eercises-

    30

    http://realpython.com/http://docs.python.org/library/stdtypes.html#string-formattinghttp://docs.python.org/library/stdtypes.html#string-formattinghttp://realpython.com/
  • 8/10/2019 Real Python

    31/209

    Real Python RealPython.com

    Create a loat o%(ect Fa decimal num%er named wei'ht that holds the

    'alue ?.*$ and create a string o%(ect named animal that holds the 'alue

    newt$ then use these o%(ects to printthe ollo"ing line withoutusing

    the format()string method7

    ?.* 1' is the wei'ht of the newt.

    isplay the same line using format()and empty {}place+holders

    isplay the same line using {}place+holders that use the index num%ers o

    the inputs pro'ided to the format()method

    isplay the same line %y creating ne" string and loat o%(ects inside o theformat()method

    . #ind a string in a string

    ne o the most useul string methods is find(). As its name implies$ "e can use

    this method to ind the location o one string in another string. )e use dot

    notation %ecause this method belongsto a string$ and the input "e supply in

    parentheses is the string "e&re searching or7@

    >>> phrase + "the surprise is in here somewhere"

    >>> print phrase.find("surprise")

    >>>

    )e&re searching or the location o the string surprise in our phrasestring. he'alue that find()returns is the indexo the irst occurrence o that string. n this

    case$ surprise starts at the thcharacter into the phrase Fremem%er to start

    counting at 0$ so "e displayed .

    find()doesn'tind the string "e&re looking or$ it "ill return !instead7

    >>> phrase + "the surprise is in here somewhere"

    >>> print phrase.find("eLafLallaLO1ull")

    !

    31

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    32/209

    Real Python RealPython.com

    >>>

    )e can e'en call string methods on a string literaldirectly$ so in this case "e didn&t

    e'en need to create a ne" string o%(ect7

    >>> print "the surprise is in here somewhere".find("surprise")

    >>>

    Leep in mind that this matching is done exactly$ character %y character. "e had tried

    to ind -8-&$ "e "ould ha'e gotten a !.

    he part o the string "e are searching or For anyparto a string is called a substring.

    a su%string appears more than once in our string$ find()"ill (ust return the irstappearance$ starting rom the %eginning o the string. #or instance$ try out7

    >>> " put a strin' in our strin'".find("strin'")

    P

    >>>

    Leep in mind that "e still can&t mix o%(ect typesB find()"ill onlyaccept a string as its

    input. "e "ere looking or an integer inside in a string$ "e "ould still ha'e to put that

    integer 'alue in a string o its o"n7>>> "I num0er is CCC!CCC!CCCC".find("C")

    >>>

    A similar string method is replace()$ "hich "ill replace all occurrences o one

    su%string "ith a dierent string. #or instance$ let&s replace e'ery instance o the

    truth "ith the string lies in the ollo"ing7

    >>> m-tor + "7m tellin' ou the truth; he spo1e nothin' 0ut the truth9">>> print m-tor.replace("the truth", "lies")

    7m tellin' ou lies; he spo1e nothin' 0ut lies9

    >>>

    Leep in mind that calling replace()did not actually change m-torB in order to

    aect this string$ "e "ould still ha'e to reassign it to a ne" 'alue$ as in7

    >>> m-tor + m-tor.replace("the truth", "lies")

    >>>

    32

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    33/209

    Real Python RealPython.com

    9e,iew eercises-

    n one line$ display the result o trying to find()the su%string a in the

    string ///B the result should %e !

    Create a string o%(ect that contains the 'alue ersion *.?B find()the

    irst occurrence o the num%er *.?inside o this string %y irst creating a

    loat o%(ect that stores the 'alue *.?as a loating+point num%er$ then

    con'erting that o%(ect to a string using the str()unction

    )rite and test a script that accepts user input using raw=input()$ then

    displays the result o trying to find()a particular letter in that input

    Assignment 3.3: Turn your user into a l33t h4x0r

    Write % scri*t Dtr%ns(%te.*yF th%t %sks the user or soe in*ut with theo((owin# *ro*t- &nter some teAt2

    Cou shou(d then use the replace()ethod to con,ert the tet entered by the user

    into D(eets*e%kF by %kin# the o((owin# ch%n#es to (ower=c%se (etters-

    he (etter- a becoes- he (etter- 0 becoes- P

    he (etter- e becoes-

    he (etter- l becoes-

    he (etter- o becoes- ?

    he (etter- s becoes- C

    he (etter- t becoes- Q

    Cour *ro#r% shou(d then dis*(%y the resu(tin# out*ut. s%*(e run o the *ro#r%with the user in*ut in bo(d is shown be(ow-

    >>> &nter some teAt2 I like to eat eggs and spam. i1 Q? Q ''C nd Cpm.>>>

    ?

    33

    http://realpython.com/http://en.wikipedia.org/wiki/Leethttp://en.wikipedia.org/wiki/Leethttp://realpython.com/
  • 8/10/2019 Real Python

    34/209

    Real Python RealPython.com

    4) /und%ent%(s- /unctions %nd oo*s

    .1 o uturistic arithmetic

    e already did some %asic math using >8&s interacti'e "indo". #or instance$ "e

    sa" that "e could e'aluate simple expressions (ust %y typing them in at the

    prompt$ "hich "ould display the ans"er7

    )>>> R K (R)

    *>>>

    6o"e'er$ (ust putting that line into a script7

    R K (R)

    "ould %e useless since "e ha'en&t actually told the program to do anything. "e "ant

    to display the result rom a program$ "e ha'e to rely on the printcommand again.

    :o ahead and open a ne" script$ sa'e it as arithmetic.py and try displaying the resultso some %asic calculations7

    print " +",

    print "* K (* ) +", * K (*)

    print ".* B ?. +", .* B ?.

    print "C B * +", C B *

    6ere "e&'e used a single printstatement on each line to com%ined t"o pieces o

    inormation %y separating the 'alues "ith a comma. he results o the numerical

    expressions on the right "ill automatically %e calculated "hen "e display it.

    (( o the s*%ces we inc(uded %bo,e were entire(y o*tion%( but they he(* to%kes thin#s e%sier to re%d.A

    )hen you sa'e and run this script$ it displays the results o your printcommands as

    ollo"s7

    >>>

    34

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    35/209

    Real Python RealPython.com

    + *

    * K (* ) + ?

    .* B ?. + .?

    C B * + *

    >>>

    )ait a second... J = 2 M 2/ #or a computer$ that doesn&t sound 'ery accurate3

    5nortunately$ the mathematics aicionados Fread7 N%er+nerds "ho de'eloped Python

    made di'ision a little counter+intuiti'e at the cost o %eing technically correct. !ince

    "e&re di'iding t"o integers Fi.e.$ "hole num%ers$ Python is doing integerdi'ision and

    ignoring the remainder.

    !ince this is an annoying ,uirk that "e usually don&t "ant$ "e ha'e to change ho"

    Python treats di'ision %y adding this %i*arre line once at the 'ery %eginning o our

    script7

    from ==future== import diision

    hat&s ==future=="ith double underscore characters Ft"o I&s on each side. I *roise

    th%t this is the (e%st sensib(e (ine o code I wi(( e,er h%,e you write.Oust remem%er

    to add it to the top o any script "here you might "ant to di'ide one integer %y another$

    and all "ill %e "ell. Coincidentally$ normal di'ision %y deault is one o the e" useulchanges in Python $ hence "hy "e need to importthis unctionality rom the

    uture.

    I you reallyw%nted to do inte#er di,ision ust use the //o*er%tor inste%d. /orinst%nceC BB * + *$ e,en i you,e %(re%dy i*orted uturistic di,ision.

    his on(y %**(ies to the BBo*er%tor. he KKo*er%tor is soethin# dierent

    entire(y %nd %ctu%((y c%(cu(%tes one nuber r%ised to the *ower o %nother nuber.

    /or inst%nce C KK * + *C.

    A

    -o" that "e&'e imported the a%ility to di'ide integers correctly$ "e can run a script like

    this7

    from ==future== import diision

    print "B* +", B*

    And "e&ll get the expected result o B* + ?.Cinstead o ?.

    35

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    36/209

    Real Python RealPython.com

    6o"e'er$ notice that i "e try to e'aluate B*in the interacti'e "indo"$ "e still get ?

    as our ans"er ? e'en ater running our ne" script. his is %ecause "e ha'en&t actually

    added this ne" di'ision unctionality to the interacti'e "indo". Dut "e can al"ays do

    that separately as "ell7

    >>> from ==future== import diision

    >>> B*

    ?.C

    >>>

    And no" our interacti'e "indo" "ill also di'ide num%ers the "ay "e "ould expect.

    9e,iew eercises-

    n a script$ printthe result o di'iding one integer %y a second$ larger

    integerB this is integer division

    mport di'ision rom the uture into the same script$ then sa'e and rerun

    the scriptB compare these results to the pre'ious 'ersion

    Assignment 4.1: Perform calculations on user input

    Write % scri*t De*onent.*yF th%t recei,es two nubers ro the user %nddis*(%ys the resu(t o t%kin# the irst nuber to the *ower o the secondnuber. s%*(e run o the *ro#r% shou(d (ook (ike this @with e%*(e in*ut

    th%t h%s been *ro,ided by the user hi#h(i#hted in bo(d)- >>>

    &nter a 0ase2 1. &nter an eAponent2 ! .* to the power of + .Q*P >>>

    Kee* the o((owin# in ind-

    = In Python y

    is c%(cu(%ted by usin# the e*ression A KK = :eore you c%n do %nythin# with the users in*ut you wi(( h%,e to store

    the resu(ts o both c%((s to raw=input()in new obects

    = he raw=input()unction returns % strin# obect so you wi(( need to

    con,ert the users in*ut into nubers in order to do %rithetic on the= Cou shou(d use the strin# format()ethod to printthe resu(t

    = Cou c%n %ssue th%t the user wi(( enter %ctu%( nubers %s in*ut

    ?

    36

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    37/209

    Real Python RealPython.com

    .2 Create your o"n unctions

    ne o the main %eneits o programming in Python is the ease "ith "hichdierent parts and pieces o code can %e put together in ne" "ays. hink o it

    like %uilding "ith >ego %ricks instead o ha'ing to crat e'erything %y hand each time

    you start a pro(ect.

    @he >ego %rick o programming is called afunction. A unction is %asically a miniature

    programB it accepts input and produces output. )e&'e already seen some examples o

    unctions such as the find()string method ? "hen called on a string$ it takes some

    input and returns the location o that input "ithin the string as its output.

    )e could create our o"n unction that takes a num%er as its input and produces the

    s,uare o that num%er as its output. n Python$ this "ould look like7

    def sSuare(num0er)2

    sSr=num + num0er K num0er

    return sSr=num

    he defis short or deine and lets Python kno" that "e are a%out to deine a ne"

    unction. n this case$ "e called the unction sSuareand ga'e it one input 'aria%le Fthe

    part in parentheses named num0er. A unction&s input is called an argumento the

    unction$ and a unction can take more than one argument.

    he irst line "ithin our unction multiplies num0er%y itsel and stores the result in a

    ne" 'aria%le named sSr=num. hen the last line o our unction returns the 'alue o

    sSr=num$ "hich is the outputo our unction.

    you (ust type these three lines into a script$ sa'e it and run it$ nothing "ill happen.he unction doesn&t do anything %y itsel.

    6o"e'er$ no" "e can usethe unction later on rom the main section o the script. #or

    instance$ try running this script7

    def sSuare(num0er)2

    sSr=num + num0er KK *

    return sSr=num

    input=num + C

    37

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    38/209

    Real Python RealPython.com

    output=num + sSuare(input=num)

    print output=num

    Dy saying output=num + sSuare(input=num)$ "e are calling up the unction

    sSuareand pro'iding this unction "ith the input 'aria%le input=num$ "hich in thiscase has a 'alue o C. @ur unction then calculates J2and returns the 'alue o the

    'aria%le sSr=num$ "hich gets stored in our ne" 'aria%le output=num.

    >otice the co(on %nd the indent%tion %ter we deined our unction. hese%rent o*tion%(A his is how Python knows th%t we %re sti(( inside o theunction. s soon %s Python sees % (ine th%t isnt indented th%ts the end o the

    unction. Every line inside the function must be indented!A9ou can deine many unctions in one script$ and unctions can e'en reer to each other.

    6o"e'er$ it&s important that a unction has %een deined beforeyou try to use it. #or

    instance$ try running this code instead7

    input=num + C

    output=num + sSuare(input=num)

    print output=num

    def sSuare(num0er)2

    sSr=num + num0er K num0er

    return sSr=num

    6ere "e&'e (ust reordered the t"o parts o our script so that the main section comes

    %eore the unction. he pro%lem here is that Python runs through our code rom the top

    to the %ottom ? so "hen "e call the sSuareunction on the second line$ Python has no

    idea "hat "e mean yet %ecause "e don&t actually deine the sSuareunction until later

    on in the script$ and it hasn&t gotten there yet. nstead "e see an error7

    6ame&rror2 name 7sSuare7 is not defined

    o create a unction that uses more than one input$ all "e need to do is separate each

    argumento the unction "ith a comma. #or instance$ the ollo"ing unction takes t"o

    arguments as input and returns the dierence$ su%tracting the second num%er rom the

    irst7

    def return$ifference(num, num*)2

    return num T num*

    38

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    39/209

    Real Python RealPython.com

    o call this unction$ "e need to supply it "ith t"o inputs7

    print return$ifference(, C)

    his line "ill call our ne" return$ifference()unction$ then display the result o !*that the unction returns.

    nce % unction returns % ,%(ue with the returnco%nd the unction is done

    runnin#G i %ny code %**e%rs inside the unction afterthe returnst%teent it

    wi(( ne,er be run bec%use the unction h%s %(re%dy returned its in%( resu(t.A@ne last helpul thing a%out unctions is that Python allo"s you to add special comments

    called docstrings. A docstring ser'es as documentation$ helping to explain "hat a

    unction does and ho" to use it. hey&re completely optional$ %ut can %e helpul i

    there&s any chance that you&ll either share your code "ith someone else or i you e'er

    come %ack to your code later$ once you&'e orgotten "hat it&s supposed to do ? "hich is

    "hy you should lea'e comments in the irst place3 A docstring looks (ust like a multi+line

    comment "ith three ,uotation marks$ %ut it hasto come at the 'ery %eginning o a

    unction$ right ater the irst deinition line7

    def return$ifference(n, n*)2

    """eturn the difference 0etween two num0ers.

    -u0tracts n* from n."""

    return n ! n*

    he %eneit o this F%esides lea'ing a helpul comment in the code is that "e can no"

    use the help()unction to get inormation a%out this unction. Assuming "e deined

    this unction %y typing it in the interacti'e "indo" or"e already ran a script "here it

    "as deined$ "e can no" type help(return$ifference)and see7

    >>> help(return$ifference)

    Help on function return$ifference in module ==main==2

    return$ifference(n, n*)

    eturn the difference 0etween two num0ers.

    -u0tracts n* from n.

    >>>

    @ course$ you can also call help()on the many other Python unctions "e&ll see to get

    39

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    40/209

    Real Python RealPython.com

    a ,uick reerence on ho" they are used.

    9e,iew eercise-

    )rite a cu0e()unction that takes a num%er and multiplies that num%er %yitsel t"ice o'er$ returning the ne" 'alueB test the unction %y displaying the

    result o calling your cu0e()unction on a e" dierent num%ers

    )rite a unction multipl()that takes t"o num%ers as inputs and multiples

    them together$ returning the resultB test your unction %y sa'ing the result o

    multipl(*, C)in a ne" integer o%(ect and printing that integer&s 'alue

    Assignment 4.2: on!ert temperatures

    Write % scri*t Dte*er%ture.*yF th%t inc(udes two unctions. ne unctiont%kes % 8e(sius te*er%ture %s its in*ut con,erts th%t nuber into theeui,%(ent /%hrenheit te*er%ture %nd returns th%t ,%(ue. he second unction

    t%kes % /%hrenheit te*er%ture %nd returns the eui,%(ent 8e(sius te*er%ture.est your unctions by *%ssin# in*ut ,%(ues to the %nd *rintin# the out*ut resu(ts.

    /or testin# your unctions e%*(e out*ut shou(d (ook (ike- Q* de'rees 3 + **.********** de'rees @

    Q de'rees @ + UP.R de'rees 3

    In c%se you didnt w%nt to s*end % inute se%rchin# the web or doin# %(#ebr% @thehorrorA) the re(e,%nt con,ersion oru(%s %re-

    / M 8 N &O5 328 M @/ J 32) N 5O&

    ?

    . Run in circles

    ne ma(or %eneit o computers is that "e can make them do the same exact thing

    o'er and o'er again$ and they rarely complain or get tired. he easiest "ay to

    program your computer to repeat itsel is "ith a loop.

    @here are t"o kinds o loops in Python7 forloops and whileloops. he %asic idea

    %ehind any kind o loop is to run a section o code repeatedly as long as a speciic

    statement Fcalled the test condition is true. #or instance$ try running this script that

    40

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    41/209

    Real Python RealPython.com

    uses a whileloop7

    n +

    while (n < C)2

    print "n +", n

    n + n

    print "%oop finished9"

    6ere "e create a 'aria%le nand assign it a 'alue o . hen "e start the whileloop$

    "hich is organi*ed in a similar "ay to ho" "e deined a unction. he statement that "e

    are testing comes in parentheses ater the whilecommandB in this case "e "ant to

    kno" i the statement n < Cis true or alse. !ince 1 J$ the statement is true and "e

    enter into the loop ater the colon.

    >otice the indent%tion on the (ines %ter the co(on. Qust (ike when we deined %unction this s*%cin# is i*ort%ntA he co(on %nd indentin# (et Python knowth%t the net (ines %re insidethewhile(oo*. s soon %s Python sees % (ine th%t

    isnt indented th%t (ine %nd the rest o the code %ter it wi(( be considered outsideo the (oo*.

    A

    @nce "e&'e entered the loop$ "e print the 'alue o the 'aria%le n$ then "e add to its

    'alue. -o" nis 2$ and "e go bacto test our "hile statement. his is still true$ since 2

    J$ so "e run through the next t"o lines o code again; And "e keep on "ith this pattern

    whilethe statement n < Cis true.

    As soon as this statement %ecomes alse$ "e&re completely done "ith the loopB "e (ump

    straight to the end and continue on "ith the rest o the script$ in this case printing out

    %oop finished9

    :o ahead and test out dierent 'ariations o this code + and try to guess "hat your

    output "ill %e %eore you run each script. Oust %e careul7 it&s easy to create "hat&scalled an infinite loopi you test a statement that&s al"ays going to %e true$ you "ill

    ne'er %reak out o the loop$ and your code "ill (ust keep running ore,er.4

    Its i*ort%nt to be consistent with indent%tion too. >otice how you c%n hit t%b%nd b%cks*%ce to ch%n#e indent%tion %nd I'+ %uto%tic%((y inserts our s*%cech%r%cters? h%ts bec%use you c%nt i t%bs %nd s*%ces %s indent%tion.

    (thou#h I'+ wont (et you %ke this ist%ke i you were to o*en your scri*t in %dierent tet editor %nd re*(%ce soe o the s*%ce indent%tion with t%bs Python

    A ...or at least until you manage to orci%ly ,uit out o >8 using your panic key com%ination o choice.

    41

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    42/209

    Real Python RealPython.com

    wou(d #et conused J e,en thou#h the s*%cin# looksthe s%e to youA

    @Cou coulduse t%b ch%r%cters e,erywhere %s indent%tion J or e,en use % dierentnuber o s*%ce ch%r%cters J %s (on# %s you %(w%ys use the samety*e o indent%tion

    or % *%rticu(%r section o indented tet.)

    he second type o loop$ a forloop$ is slightly dierent in Python. )e typically use for

    loops in Python in order to loop o'er e'ery indi'idual item in a set o similar things?

    these things could %e num%ers$ 'aria%les$ lines rom an input ile$ etc.

    #or instance$ the ollo"ing code does the exact same thing as our pre'ious script %y

    using a forloop to repeatedly run code or a ran'eo num%ers7

    for n in ran'e(, C)2

    print "n +", n

    print "%oop finished9"

    6ere "e are using the ran'e()unction$ "hich is a unction that is %uilt into Python$ to

    return a list o num%ers.Jhe ran'e()unction takes t"o input 'alues$ a starting

    num%er and a stopping num%er. !o in the irst line$ "e create a 'aria%le ne,ual to $

    then "e run through the code inside o our loop or n + .

    )e then run through the loop again or n + *$ etc.$ all the "ay through our range o

    num%ers. @nce "e get to the end o the ran'e$ "e (ump out o the loop. 9es$ it&s

    slightly counter+intuiti'e$ %ut in Python a ran'e(A, )starts at A%ut ends right

    before.

    When we use % or(oo* we dont need to deine the ,%ri%b(e we(( be (oo*in#

    o,er irst. his is bec%use the or(oo* re%ssi#ns % new ,%(ue to the ,%ri%b(e

    e%ch tie we run throu#h the (oo*. In the %bo,e e%*(e we %ssi#ned the

    ,%(ue 1to the obect n%s soon %s we st%rted the (oo*. his is dierent ro %while(oo* where the irst thin# we do is to test soe condition J which is why we

    need to h%,e #i,en % ,%(ue to %ny ,%ri%b(e th%t %**e%rs in thewhile(oo* beforewe

    enter the (oo*.APlay around "ith some 'ariations o this script to make sure you understand ho" the for

    J you ha'e a 'ery large ran'e()o integers and memory considerations are an issue$ then you shoulduse the unction Aran'e()$ "hich "orks the exact same "ay as ran'e()and is more eicient. his is%ecause Aran'e()looks through the integers one at a time$ "hile ran'e()creates the ull list o

    num%ers irst. Fn Python $ ran'e()"orks like Aran'e()$ "hich in turn no longer exists.

    42

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    43/209

    Real Python RealPython.com

    loop is structured. Again$ %e sure to use the exactsame syntax$ including the in

    key"ord$ the colon$ and the proper indentation inside the loop.

    'ont ust co*y %nd *%ste the s%*(e code into % scri*t = ty*e it out yourse(A>ot on(y wi(( th%t he(* you (e%rn the conce*ts but the *ro*er indent%tion wontco*y o,er correct(y %nyw%yRA

    As long as "e indent the code correctly$ "e can e'en put loops inside loops3 ry this out7

    for n in ran'e(, )2

    for L in 4"a", "0", "c"52

    print "n +", n, "and L +", L

    6ere Lis looping o'er a list o stringsB "e&ll see ho" lists "ork in a later chapter$ %ut thisexample is only to sho" that you don&t haveto use the ran'e()unction "ith a for

    loop. !ince the Lloop is insidethe nloop$ "e run through the entire Lloop FL+"a",

    L+"0", L+"c" or each 'alue that gets assigned to nin the outer loop.

    )e "ill use forloops in uture chapters as an easy "ay to loop o'er all the items stored

    in many dierent types o o%(ects ? or instance$ all the lines in a ile.

    nce your code is runnin# in the inter%cti,e window soeties you i#ht%ccident%((y end u* enterin# % (oo* th%t t%kes uch (on#er th%n you e*ected.I th%ts the c%se @or i your code sees DroenF bec%use o %nythin# e(se th%ts

    t%kin# (on#er th%n e*ected) you c%n usu%((y bre%k out o the code by ty*in#@%@in the inter%cti,e window. his shou(d iedi%te(y sto* the rest o your

    scri*t ro runnin# %nd t%ke you b%ck to % *ro*t in the inter%cti,e window.

    I th%t doesnt see to h%,e %ny eect @bec%use you soehow %n%#ed to reeethe I'+ window) you c%n usu%((y ty*e @%Vto uit out o I'+ entire(y uch

    (ike D+nd %skF in Windows or D/orce

  • 8/10/2019 Real Python

    44/209

    Real Python RealPython.com

    a whileloop instead o a forloop in this case$ %ut it&s good practice;

    )rite a unction dou0les()that takes one num%er as its input and dou%les

    that num%er three times using a loop$ displaying each result on a separatelineB test your unction %y calling dou0les(*)to display $ P$ and R

    Assignment 4.3: Track your in!estments

    Write % scri*t Din,est.*yF th%t wi(( tr%ck the #rowin# %ount o %n in,estento,er tie. his scri*t inc(udes %n inest()unction th%t t%kes threein*uts-

    the initi%( in,estent %ount the %nnu%( co*oundin# r%te %nd the tot%(

    nuber o ye%rs to in,est. $o the irst (ine o the unction wi(( (ook (ike this-

    def inest(amount, rate, time)2

    he unction then *rints out the %ount o the in,estent or e,ery ye%r o thetie *eriod.6In the %in body o the scri*t @%ter deinin# the unction) use theo((owin# code to test your unction-

    inest(??, .?C, P)inest(*???, .?*C, C)

    9unnin# this test code shou(d *roduce the o((owin# out*ut exactly-

    principal amount2 W??annual rate of return2 ?.?Cear 2 W?C.?ear *2 W?.*Cear 2 WC.QR*Cear 2 W*.CC?R*Cear C2 W*Q.R*PCR*Cear R2 W.??UCR?Rear Q2 W?.Q??**RR

    ear P2 WQ.QCCQU

    principal amount2 W*???annual rate of return2 ?.?*Cear 2 W*?C?.?ear *2 W*?.*Cear 2 W*C.QP*Cear 2 W**?Q.R*CQP*Cear C2 W**R*.PR*CQP

    ?

    Q he only math in'ol'ed here is that the initial Fprincipal in'estment amount is multiplied %y 1 H the

    annual return rate e'ery year. #or instance$ ater one year at a 0.0J rate$ 100 100 x 1.0J M 10J.

    44

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    45/209

    Real Python RealPython.com

    Hint-(thou#h unctions usu%((y returnout*ut ,%(ues this is entire(y o*tion%( in

    Python. /unctions these(,es c%n printout*ut direct(y %s we((. Cou c%n print%s

    uch %s you (ike ro inside % unction %nd the unction wi(( continue runnin# unti(

    you re%ch its end.

    $oe %ddition%( *ointers i youre stuck-= Cou wi(( need to use % for(oo* o,er % ran'eth%ts b%sed on

    the unctions timein*ut.

    = Within your (oo* you wi(( need to re%ssi#n % new,%(ue to theamounte,ery ye%r b%sed on how it #rows %t rate.

    = 9eeber th%t you need to use either the strin# format()ethod orstr()to con,ert nubers to strin#s irst i you w%nt toprintboth

    strin#s %nd nubers in % sin#(e st%teent.

    = sin# the printst%teent by itse( wi(( *rint % b(%nk (ine.

    45

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    46/209

    Real Python RealPython.com

    Interlude- 'ebu# your code

    ou&'e pro%a%ly already disco'ered ho" easy it is to make mistakes that >8 can&t

    automatically catch or you. As your code %ecomes longer and more complicated$ it

    can %ecome a lot more diicult to track do"n the sources o these errors.9)hen "e learned a%out syntaxand run-timeerrors$ actually let out a third$ most

    diicult type o error that you&'e pro%a%ly already experienced7 the logic error. >ogic

    errors occur "hen you&'e "ritten a program that$ as ar as your computer is concerned$

    is a completely 'alid program that it has no trou%le running ? %ut the program doesn&tdo "hat you intended it to do %ecause you made a mistake some"here.

    Programmers use debuggersto help get these %ugs out o their programs F"e&re cle'er

    "ith names like that$ and there&s already a simple de%ugger %uilt into >8 that you

    should learn to use + %eore you needto use it.

    (thou#h debu##in# is the (e%st #(%orous %nd ost borin# *%rt o *ro#r%in#(e%rnin# to %ke #ood use o % debu##er c%n s%,e you % (ot o tie in the end.We %(( %ke ist%kesG its % #ood ide% to (e%rn how to ind %nd i the.

    A#rom the ile menu o the interacti'e "indo" o >8 Fnotin a script "indo"$ click one%ug e%ugger to open the e%ug Control "indo".

    -otice ho" the interacti'e "indo" no" sho"s 4$&JX 65at the prompt to let you

    kno" that the de%ugger is open. )e ha'e a e" main options a'aila%le to us$ all o

    "hich "ill %e explained shortly7 "o$ $te*$ ,er$ ut$ and

  • 8/10/2019 Real Python

    47/209

    Real Python RealPython.com

    > 7==main==7.(), line 2 for i in ran'e(,)2

    All this is telling us is that line 1 F"hich contains the code for i in ran'e(,)2

    is a%out to %e run. he %eginning o the !tack line in the de%ugger reers to the act

    that "e&re currently in the main section o the script ? or instance$ as opposed to

    %eing in a unction deinition %eore the main %lock o code has %een reached.

    he de%ugger allo"s us to step through the code line %y line$ keeping track o all our

    'aria%les as "e go. !o$ let&s go ahead and click once on $te* in the de%ugger in order

    to do that. )atch careully "hat happens to the de%ugger "indo" "hen you do that;

    -o" the !tack "indo" in the de%ugger says that "e&re a%out to run line 2 o the code$

    "hich means that line 1 has %een executed. Delo" that$ the :lo%als and >ocals"indo" includes a ne" 'aria%le ithat&s %een assigned the 'alue . his is %ecause the

    forloop in the irst line o our code created this integer iand ga'e it that starting

    'alue. Fhere are also a e" internal system 'aria%les listed a%o'e it$ %ut "e can ignore

    those.

    Continue hitting the $te* %utton to "alk through your code line %y line$ "atching

    "hat happens in the de%ugger "indo". 9ou can track the gro"ing 'alues o iand Las

    you loop through the forstatement$ and output is displayed in the interacti'e "indo"

    as usual "hen the printstatements are run.

    5sually$ "e only "ant to de%ug a particular section o the code$ so spending all day

    clicking the $te* %utton is less than ideal. his is the idea %ehind setting a

    breapoint.

    Dreakpoints tell the de%ugger "hen to start pausing your code. hey don&t actually brea

    anythingB they&re more like hang on a second$ let me take a look at things irst+points.

    >et&s learn to use %reakpoints %y "orking "ith the ollo"ing example code$ "hich isn&t

    ,uite doing "hat "e "ant it to do yet7

    def addnderscores(word)2

    new=word + "="

    for i in ran'e(?, len(word))2

    new=word + word4i5 "="

    return new=word

    47

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    48/209

    Real Python RealPython.com

    phrase + "hello9"

    print addnderscores(phrase)

    )hat "e meantor the unction addnderscores()to do "as to add underscores

    around e'ery character in the "ord passed to it$ so that "e could gi'e t the inputhello9 and it "ould return the output7

    =h=e=l=l=o=9=

    nstead$ all "e see right no" is7

    9=

    t might already %e o%'ious to you "hat our error "as$ %ut let&s use the de%ugger to

    "ork through the pro%lem. )e kno" that the pro%lem is occurring some"here inside inthe unction ? speciically$ "ithin the forloop$ since "e said that new=wordshould

    start "ith a = %ut it clearly doesn&t. !o let&s put a %reakpoint at the start o the for

    loop so that "e can trace out exactly "hat&s happening inside.

    o set a %reakpoint on a line$ right+click F4ac7 control+click on that line and select $et

    :re%k*oint$ "hich should highlight the line to let you kno" that the %reakpoint is

    acti'e.

    -o" "e can run the script "ith the de%ugger open. t "ill still pause on the 'ery irst

    line it sees F"hich is deining the unction$ %ut "e can select "o to run through the

    code normally. his "ill sa'e the unction in Python&s memory$ sa'e the 'aria%le phrase

    as hello3$ call up our unction rom the printstatement; and thenpauseat our

    %reakpoint$ right %eore entering the forloop.

    At this point$ "e see that "e ha'e t"o local 'aria%les deined Fthey&re local %ecause

    they %elong to the unction. As expected$ "e ha'e new=word$ "hich is a string "ith

    (ust the underscore character$ and "e ha'e word$ the 'aria%le "e passed to the

    unction$ "ith hello3 as its contents.

    Click $te* once and you&ll see that "e&'e entered the forloop. he counter "e&re

    using$ i$ has %een gi'en its irst 'alue o ?.

    Click $te* one more time$ and it might %ecome clearer "hat&s happening in our code.

    he 'aria%le new=wordhas taken on the 'alue h=; t got rid o our irst underscore

    48

    http://realpython.com/http://realpython.com/
  • 8/10/2019 Real Python

    49/209

    Real Python RealPython.com

    character already3 you click $te* a e" more times$ you&ll see that new=wordgets

    set to e=$ then l=$ etc. )e&'e %een o'er"riting the contents o new=wordinstead

    o adding to it$ and so "e correct the line to7

    new=word + new=word word4i5 "="

    @ course$ the de%ugger couldn&t tell us exactly howto ix the pro%lem$ %ut it helped us

    identiy wherethe pro%lem occurred and "hat exactly the unexpected %eha'ior "as.

    9ou can remo'e a %reakpoint at any time %y right+clicking F4ac7 control+clicking and

    selecting 8(e%r :re%k*oint.

    n the de%ugger$

  • 8/10/2019 Real Python

    50/209

    Real Python RealPython.com

    you thought they should look at that point.

    #or instance$ in the pre'ious example "e could ha'e added the statement print

    new=word inside o our forloop. hen "hen "e run the script$ "e&d %e a%le to see

    ho" new=wordactually gro"s For in this case$ ho" it doesn&t gro" properly. Oust %e

    careul "hen using printstatements this "ay$ especially inside o loops ? i you don&t

    plan out the process "ell$ it&s easy to end up displaying thousands o lines that aren&t

    inormati'e and only end up slo"ing do"n or ree*ing your program.

    @r you could al"ays try ru%%er ducking.

    50

    http://realpython.com/http://en.wikipedia.org/wiki/Rubber_duck_debugginghttp://en.wikipedia.org/wiki/Rubber_duck_debugginghttp://realpython.com/
  • 8/10/2019 Real Python

    51/209

    Real Python RealPython.com

    5) /und%ent%(s- 8ondition%( (o#ic

    J.1 Compare 'alues

    omputers understand our "orld in %inary$ %reaking e'ery pro%lem do"n into 0&s

    and 1&s. n order to make comparisons %et"een 'alues$ "e ha'e to learn ho" to

    communicate in this 1 or 0 language using boolean logic. Doolean reers to anything

    that can only take on one o t"o 'alues7 true or alse.

    C

    o help make this more intuiti'e$ Python has t"o special key"ords that are con'eniently

    named rueand 3alse. he capitali*ation is important ? these key"ords are not

    ordinary 'aria%les or strings$ %ut are essentially synonyms or 1 and 0$ respecti'ely. ry

    doing some arithmetic in the interacti'e "indo" using rueand 3alseinside o your

    expressions$ and you&ll see that they %eha'e (ust like 1 and 07

    >>> * K rue 3alse

    *

    >>> 3alse K * ! !

    >>> rue ?.* B rue

    .*

    >>>

    Deore "e can e'aluate expressions to determine "hether or not they are rueor

    3alse$ "e need a "ay to compare 'alues to each other. )e use a standard set o

    sym%ols Fcalled boolean comparators to do this$ and most o them are pro%a%ly already

    amiliar to you7

    a > 0 a greater than 0

    a < 0 a less than 0

    a >+ 0 a greater than or e#$al to 0

    a

  • 8/10/2019 Real Python

    52/209

    Real Python RealPython.com

    he last t"o sym%ols might re,uire some explanation. he sym%ol 9+ is a sort o

    short+cut notation or saying not e,ual to. ry it out on a e" expressions$ like these7

    >>> 9+ *

    rue>>> 9+

    3alse

    >>>

    n the irst case$ since 1 does not e,ual 2$ "e see the result rue. hen$ in the second

    example$ 1 doese,ual 1$ so our test expression 9+ returns 3alse.

    )hen "e "ant to test i ae,uals 0$ "e