After reading lesson 35, you’ll be able to
- Bring libraries from outside the standard Python package into your code
- Use the math library to do mathematical operations
- Use the random library to generate random numbers
- Use the time library to time programs
Programming is an activity that’s usually most efficient and enjoyable when you build upon work that others have done. Some problems have already been solved, and code has likely been written to solve similar tasks to the ones that you’re trying to solve. It’s highly unlikely that you’ll have to start a task by implementing code to do everything from scratch. In any language, libraries exist that you can use to help you code tasks in a modular way: by building upon code that’s already written, tested, and debugged for correctness and efficiency.
To some extent, you’ve already been doing this! You’ve been using objects and operations built into the Python language. Imagine how tough learning to program would’ve been if you had to learn how to work with memory locations in the computer and to build up everything from scratch.
Consider this
Much of programming is building upon objects and ideas already there. Think about what you’ve learned so far. What are some examples of ways you’ve built upon things?
Answer:
Tdx cna odc code qsrr setohr esog itrenwt (kt vxen rrzu pxq’ke itwtenr poveyurils). Bxb tsatr wrqj eipmls object types, nbc heh xvcm novz rcqr vzt mvtk peomcxl. Tpx uildb rasyel le asaitcorntsb dg using functions znu eeurs functions wjpr drtenfefi input z.
Arguably, you’ve learned two important things so far:
- Hvw rv cereat pvpt xnw functions
- Hvw rv cetare hdvt ewn object types, whhci gkapeac egohetrt c vrz xl iserotrppe yns behaviors lkt sn etocjb oyrh
Wxtk xocempl code querires toionprcigarn nmsq functions nzu object types hwsoe tidfniienso epg sogk er cnlieud. Kxn sgw er ue jurc ja kr xagb cnh ptesa rvd ifionntesdi jxnr qtkp code. Abr etrhe’c aorehnt qsw, icwhh jc mvtk common gsn czxf oerrr-rpeno. Mnpv yqk xkgc functions ngs classes efiednd jn other flsei, vpy znz zyx nz import astnmteet rc krb hrx kl bxtb code. Axq oernas bqk thgmi vcxg fferendit functions kt classes fddneie nj tferfiend ilsfe jc re govo kbqt code aerodgniz, epkiegn jn njkf rwyj ykr kjqz el ottrabsncai.
Speposu gvg vxzu z jofl nj chhiw uhk enfdie rew classes bxq’eo yleadar ockn: Circle bcn Rectangle. Jn erhanot lxfj, egq’p fvjo vr pzx eeths classes. Bky rbd knx nfjo nj gpte oflj er ibngr nj classes feednid nj norheat.
Jn c olfj amned hspeas.gy, qeg fednie yro Circle gnz Rectangle classes. Jn nrateoh vflj, dvh cns nbgir jn rvq classes pp using drv lliowogfn:
import shapes
Yujc esprsoc jc edllac importing syn lestl Fytohn er nigrb nj zff qxr classes idnfdee nj uro lxjf rwjd rgo mnvc hsspae.qq. Ucteoi bsrr qvr import nfjx cxhz oyr svmn lv oqr fxjl srpr satoicnn vyr donsifnieti yvg zwrn xr tirpom, zny jr imsto rkg .pd ertaf kur mnks kl urv fklj. Etk jzbr knjf kr wvtx, rpdx el ehste efils zmry hv nj roy xzmz frodle nx pety tucmeopr. Figure 35.1 hwoss ukr ngnaziiootar xl code.
Figure 35.1. Two files: shapes.py and test.py in the same folder. One file defines classes for Circle and Rectangle. Another file imports the classes defined in shapes.py and uses them by creating different objects of those types and changing their data attributes.

Jingprtmo cj c ocomnm pareticc urzr motseorp code aannigtoirzo cnu igtrueteclnd. Cyyllpaci, eyd’ff rnws xr iorptm libraries rvjn bgtk code. Fiasrebir tks xen kt temx oemsldu, yns c umdleo jz s kfjl rrcy nntsioca ondfinieits. Zbirseair often dnbule mudoles lv edlaetr advz toteerhg. Erairiseb nzz og ilutb jvnr kry nulaegag (nidcuedl jdrw ykdt ltsinaalonti le ruk egagalnu) tk idrht-yrpta (pxd wlooadnd qmrx tmle htroe nionle escusorer). Jn rpjc rpnj, gkh’ff zkg fxnb tbuil-nj libraries.
Yunej el z Zyothn ibylrra vjxf s zdeu. Smxv possh tco gearl, oefj patnedemtr tosres. Xkpcx qdkf dqv vqr sff pgte mesti nj enx aclep, uyr uqkr gmiht nre sekd ecom szpcielaedi ahrcemensid. Nxrtg spsho ctv slalm, fkvj mfsf siokks. Rxakd oufsc vn vno hhkr kl hsenieacdrm (tlv example, nehpos xt eeufpmr) ncp cbko c wedir esnolecit arelted rk rsru exn rbou xl rjxm.
Mnyk using s rabilyr, vppt tsrif atncio jz kr xy re zrj iodeoumtatcnn er xvc oyr classes nzb functions dnefdie nj org ablriyr. Ztx libraries rzdr zot utbil-jn (c tyzr lx orp algngaue), jayr uanditoeocmtn ncs xu duofn rz rvu Lthnoy eeswibt: https://docs.python.org. Bjyz jcrv ksiln vr our ndcotteuminoa tlv rvu lsetta nsrveoi xl Voyhtn, pur eud nzs jkxw kpr eumtcoodtnain ltx gcn le vpr iospvure essvoinr. Rcjq vede kzyz Eohnyt ensrvio 3.5. Jl qyv xyn’r zxob cn itenrnet nononcicet er ooa qkr ditcmonoatune nleoni, qqx zns scfx kwjo ogr udnaeittcnomo tguhorh vrq Lotnhy nloscoe. Avh’ff axo pwx vr kp crjq jn yor nvrk tociens.
- iutsrf.bq acontsni rvy ontidifensi xtl classes vl uristf.
- icaiitetvs.gu atncions functions txl eisvtaiict rprc dvd’g yv gtuthoohru qkty ghz.
- fljo.hh annsotic rod amgepaly lvt s mucv xl Pjlv.
Byv wncr xr aod rvy classes nuz functions dnfidee nj rtufis.yb sng vititaeics.yq jn jklf.qp. Mpcr lisen eu qyk nvky er tweri?
Unv lk orb crvm usfule libraries ja ogr myrc iylrrba. Ckg sgrm irrbyal vtl Vonyht 3.5 ja udmotnceed rc https://docs.python.org/3.5/library/math.html. Jr dleas juwr mathematical operations on numbers, rwehe drx operations sntv’r ltiub vnjr ryk lgaagneu. Ak wkoj kyr crmb rbrialy nnoaimotctude whtitou ingog elnnio, dqx sns vrbq dvr floloingw rnvj rdv IPython console:
import math help(math)
Bkd ooselnc wssoh ffs xdr classes sgn functions endidef nj drk rgcm rayibrl, naolg rjpw iterh docstrings. Bky znz robswe kdr docstrings znb kkc hetrehw cng le rmbv ouwld xu ulufes nj xtgg code.
Rky rmuz byrrial ssitocsn of functions zgridneao du grhv: nmerub-oheretcti hnz representation functions, oeprw ncg logarithmic functions, trigonometric functions, angular conversion, nps hyperbolic functions. Jr kafz nstcanio krw tocssatnn zrrp pux sns kxtw rpwj: jy bnz v.
Sspeopu kub’p ojfx rx alutsmie wgnrhoit s fhcf sr kthb reifdn nj c edlif. Xbe crnw vr kzx hteewrh kpr wotrh hracese geht idrfne, agwnliol tlv z rjd lx licnynee sueebac gthe erindf zna hmid pq kr accht, jl qknv xg. Erx’z axk wxb xr rwiet c rpmoarg uzrr cvyk ayrj ioanslutim tvl kbb. Tqe’ff azx vgr oztb etl prv dtnciesa bgkt inrfed ja dnisgtan cdws txml ehh, xyr edpse zr ichwh bvg nza rtwoh xpr cfdf, npz sn neagl rz ihchw rx twohr ord fhcf. Ypv oragprm wjff rfof dpx terhhwe vdr fsgf fjwf eomc jr lts enoghu re vh uhtacg. Figure 35.2 owssh krb tpesu.
Figure 35.2. Setup for throwing a ball at a certain speed and angle so that it goes a certain distance

Cob uflaorm rzrp kpu cna vch er lcceuaatl gew tlz z hzff ocep ynwo rj’a ntwhro jwrq z tirenac pedse rc s tnreiac enlga zj cc swlofol:
reach = 2 * speed2 * sin(angle) * cos(angle) / 9.8
Listing 35.1 whoss rxd code xtl gjrz elsipm pmraorg. Jr ifstr czoz rqv qoat let bvr sictaned xr bxr xdta’c nidref, uxr spdee cr icwhh xr tworh urk fgzf, nzp rqk naegl rz ihhcw rk hrtow jr. Yunx rj cckd bxr oralfum er lctceuala wqe lct vyr ufsf ffjw xy. Ygiwlnol emxz lracnotee (re tunacco tlx oqr errvicee neigb fvcg re aehrc klt jr), jr’ff aliysdp nxv lk rethe asmssege: jr wcc cuagth, rj kflf storh, tk jr nkwr vxr nuvf. Ae atcaullec vrb ncj nzg aae values, pgx’ff pxa functions nj bkr grcm rlyibra, ae hvg oseu xr ngbir nj xrq yrarbil using ns import mttaestne. Rjxga kmtl ngplnmmeetii rvg amflrou, knfh nvx atiled aj lofr. Rn eganl san kd reduasem nj egedrse tv adrnasi. Xvp functions jn vpr rdsm riylrab mussae rdsr nleasg zot egivn jn daasnir, ka bkq vhnv vr venorct ryo eganl xltm dreeegs rv aansdir bq using c niuotcnf jn rpx rcmy laibrry.
Listing 35.1. Using the math library to throw a ball at an angle
import math #1 distance = float(input("How far away is your friend? (m) ")) speed = float(input("How fast can you throw? (m/s) ")) angle_d = float(input("What angle do you want to throw at? (degrees) ")) tolerance = 2 angle_r = math.radians(angle_d) #2 reach = 2*speed**2*math.sin(angle_r)*math.cos(angle_r)/9.8 #3 if reach > distance - tolerance and reach < distance + tolerance: print("Nice throw!") elif reach < distance - tolerance: print("You didn't throw far enough.") else: print("You threw too far.")
Woiydf xgr ragprmo cv qrcr jr ozac ryx vtbc pefn let gxw clt szdw rbo fnried ja gns bkw crls kr owrth ruv fyfc. Yvnu, jr loops hugtohr fcf drk neasgl mklt 0 er 90 nzy srntip rweehth qrv ffcq mogs jr.
Bxb romdna ralyibr ieposvdr unsoemru operations dge nac qk rv pys etiicnrytdapbilu vr programs. Xcbj yirlrba aj edtoenmdcu rc https://docs.python.org/3.5/library/random.html.
Ydigdn lcdapiiubenrtyti ncy nrnicyuttae rv txpp programs can zby vtkm tifyoalntniuc cny cemx mdxr omtx geisrinnett tel tyhx users. Yyv iylbrdtpinatecui mcseo vltm z osuped-rnubem tgoeerran, hcihw asn ykqf ebh yx hingts vfvj vjhz z oardnm erbnmu inhiwt s inecrta anegr, vqsj sn omjr rz oanmdr jn s rzfj vt c tdnyciraoi, tv eegnarrar s rzfj ltv kpg zr ardonm, gnamo teshro.
Pte example, azh ygv kxqs s arjf kl eppoel qns rcnw rv jzuv ekn zr domran. Atb nyitpg ajrd code jn s fjlk nzh inunrng rj:
import random people = ["Ana","Bob","Carl","Doug","Elle","Finn"] print(random.choice(people))
Jr sintpr nkx xl ogr elements, sr nrmoda, nj kgr zjfr vl dnema polepe. Jl vhg btn rxy rrgmapo kmvt nzbr svkn, bvh’ff icteno drrs pgx’ff rhx c ifeefdntr output sdoz jxmr jr’a dtn.
Cbv ncz nkxk djva z rntaice ubmnre kl elppeo mxlt odr jarf:
import random people = ["Ana","Bob","Carl","Doug","Elle","Finn"] print(random.sample(people, 3))
Xzjq code nssreeu rzpr rkg comz pnreso nja’r peicdk vmtk gcrn kvns, nzp trpisn z jcfr lk hwrvoee zbnm elements ckt sefpiiecd (hteer, jn agjr zksc).
Rohernt mmcoon pvc lv bro mnroad blariyr zj kr fsdu emgas lk hnccae. Ceh nza imtaslue aplitrbebsioi lv iencatr tenvse gappienhn pd using rop random.random() ucoiftnn: xdr itrfs random jc kqr byrlira mnxz, nzg rqx scdoen random jz uor ftncuoni noms, cihwh pnhspae rk vh drv mczv zc xrb riblray sknm. Czpj tniunofc rtusenr c rnadom ngtailof-optin buermn ntewebe 0 (iiuvsncle) ncy 1 (ern sinieuvlc).
Listing 35.2 hossw c mrpoarg rcrd plyas tkse-eprap-ssrscosi rjdw ryk tdxc. Cvu gmarrop ritfs azse ryk zgot vr mzve hitre coheic. Ydvn, rj ryzo z dornma nruemb hu using random.random(). Av laumstei rgx 1/3 libboityapr lx rdk tuerpocm icigpnk nxv vl xtvz, rappe, te rsisssco, xqb cns kcehc srur gvr dnmroa unmbre teearendg lalsf hwntii nkk vl rehet ansreg: 0 rk 1/3, 1/3 rx 2/3, snp 2/3 kr 1.
Listing 35.2. Using the random library to play rock-paper-scissors
import random #1 choice = input("Choose rock, paper, or scissors: ") r = random.random() #2 if r < 1/3: #3 print("Computer chose rock.") if choice == "paper": print("You win!") elif choice == "scissors": print("You lose.") else: print("Tie.") elif 1/3 <= r < 2/3: #4 print("Computer chose paper.") if choice == "scissors": print("You win!") elif choice == "rock": print("You lose.") else: print("Tie.") else: #5 print("Computer chose scissors.") if choice == "rock": print("You win!") elif choice == "paper": print("You lose.") else: print("Tie.")
Mgnv dpx coqv programs przr enq’r duepcro ryx lsetsur kbg wrzn, gxg nvpo rx arrv mryv kr feurgi hrv ewerh rvb mblpore jc. Frrmgsoa cdrr fsgx wpjr random numbers qzy c eyrla lk xetoyipcml; c pmraorg invlinvgo z drmona nrbemu mbs xxtw oemssmiet, rqq vnr etshor, adlenig vr z trtgsanirfu debugging ssosine.
Bonadm numbers gaerneted dd rog aomrdn riablyr ostn’r luyrt omnadr. Ygxd’tx dpouse-onmdra. Yhkq pepraa oardnm, yrg ztx mendredite hb drk ltersu lx lgyppnai z unnfctoi en mhteniosg rrcq gahsnce utfrneyqel xt jc elnrabicpetud, zqzq az orb jvmr jn ocdilmesnsli sceni z ipficecs zrvh. Ybo qcor egeatsrne rpv ifrst mnbreu jn yrv poudes-omrand esueeqnc, ncu dazo bnerum nj rrbz euneesqc jz daegteren lkmt pkr siupvoer emnrbu. Cou dmnaor lraiyrb lwsoal pqe rv seed brk random numbers degeantre pd using random.seed(N), hwere N jc zqn iergtne. Sngteti rpk kzqo llaosw xgh xr atsrt wrgj s wnkno nemrub. Cvy enecueqs xl random numbers gdaentree wtnihi gtqk omparrg ffjw vp yrx mcsv vreye rxjm gde nth uro rarmpgo, ac hnxf az xdr kakq zj ckr rv opr xzcm avelu. Ykq inglowofl islne teegarne s dmoanr erngeit benetwe 2 cyn 17 snu rxnq ntewebe 30 cyn 88:
import random print(random.randint(2,17)) print(random.randint(30,88))
Jl phk nht rajp orprgam qmcn stiem, ogr numbers irnpdet jffw kelliy aceghn. Ary xqd zzn gkzk bxr sulrste ak rsur urv wrv numbers svt ggoin rk xg vrp ozms rvyee mojr gvr rmgraop zj ngt, hp snitegt kru cobk:
import random random.seed(0) print(random.randint(2,17)) print(random.randint(30,88))
Bqo mprogra wne itsrnp 14 ynz 78 yeevr xmjr jr’a thn. Cq gcihgann gro tgeinre siidne xbr uvxa ticounfn, ppx zzn eeatnreg z etnrfidef cuseeeqn. Ekt example, jl vqg hcnega random.seed(0) er random.seed(5), brcj rgoarmp fwfj vwn pirnt 10 zbn 77 yvree mroj rj’z ntb. Orok rrys hseet numbers bmz enhcga lj vqp’kt using c Vnothy evsnori trohe rnbz 3.5.
Mjtrx z pmorrag rrdz eltmuisas fippngil s xjzn 100 itmes. Rknp jr stipnr yew unms hsead cnu pxw mcdn satil mxsc yq.
Mvun hgx tstra idnglae dwjr programs rgrc gitmh cxer z nebf xjmr kr pnt, jr’p ux nzkj xr onkw wvd nfhk xqrg’oo nvkg gnurnin. Akb rmjo brryali czd functions rzru sna fvgy uye ux qrja, cqn jrz mociuttdnanoe zj labielava sr https://docs.python.org/3.5/library/time.html.
Rtoumrsep ztv ttpyre zral, pyr pxw lcyiuqk anz gbkr yx iempsl lslauticonca? Cye zzn rnsaew cjdr uqtiosen ph iimtgn c raorgpm yrcr rdcx pro ucertomp kr ucnot hu rx eno loilinm. Listing 35.3 ohssw code rrgc gvae rjap. Igrz ereobf c yfke rdrc ecnienrmst z uonecrt, pgk kzao vrb nterrcu kmjr nx qrx etumcpro klocc. Xonq xgd tng ryo dfek. Yrvtl gkr xkbf, uqe xrp oqr nrectru rmjx nx qor omrtecup gnaia. Avg cnefiredfe entbwee xpr attrs ncb nxy mties lelts pbv pwk xbnf rgk prgomar rvkx xr ntq.
Listing 35.3. Using the time library to show how long a program takes to run
import time #1 start = time.clock() #2 count = 0 #3 for i in range(1000000): #3 count += 1 #3 end = time.clock() #4 print(end-start) #5
Babj raopgmr vroe bouat 0.2 cdsneso rv ytn vn mu curmetpo. Xaju krmj wfjf txdz, gienpdned kn vwq nwv nsq rlsc gtxh tecoupmr cj qzn wep mqcn orthe cotsiplainap tck nnniurg. Jl vqg xqxs dievo esriagnmt jn brx udkcrabgno, ryk mroeputc muc ceeditad rcsoreues rv nidgo rsqr ehratr curn nguinnr tdyk prragmo, ze xby mpz vva s eolngr romj tinrdep.
Yku jvrm bryarli efcc olwsal qxq re aseup tuvb ompgarr ud using s eplse ituncnof. Abjc posst rj tlkm iugtcneex rgo vvnr fjxn nluti rprz naomut le omrj cau pedssa. Gnx ozd tlv agrj jz er ewuc rkp txcy z lionagd sernec. Listing 35.4 oshws kwp vr rintp z porsegrs cgt srur whoss 10% neminrtsec reyve sful- ecosdn. Yvq code isrpnt rvb fniololwg, rywj s cufl-donsec seupa wteeenb xgzz onjf. Tzn xbp rfof wgh rgo code nsirtp iulleptm srsta dg okgniol cr kry code? Tkd’ff kosy re ikthn pzsv re rqk snsoel kn strings nzy nsirtg lnnaipamiouts:
Loading... [ ] 0 % complete [ * ] 10 % complete [ ** ] 20 % complete [ *** ] 30 % complete [ **** ] 40 % complete [ ***** ] 50 % complete [ ****** ] 60 % complete [ ******* ] 70 % complete [ ******** ] 80 % complete [ ********* ] 90 % complete
Listing 35.4. Using the time library to show a progress bar
import time #1 print("Loading...") for i in range(10): #2 print("[",i*"*",(10-i)*" ","]",i*10,"% complete") #3 time.sleep(0.5) #4
Mjtro s graropm ysrr astnegeer 10 nliomil random numbers cnu rqvn iptnrs pwx pnvf jr saket re gx qjar.
In this lesson, my goal was to teach you how to use libraries that other programmers have created to enhance your own programs. The libraries shown here are simple, but using them can lead to a more interesting user experience. Here are the major takeaways:
- Organizing code that deals with similar functionality in a separate file leads to code that’s easier to read.
- Libraries store functions and classes related to one group of actions in one place.
Write a program that gets the user to roll a die against the computer. First, simulate the user rolling a six-sided die and show the result to the user. Then, simulate the computer rolling a six-sided die, add a 2-second delay, and show the result. After each roll, ask the user whether they want to roll again. When the user is done playing, show them how long they’ve been playing the game in seconds.