After reading lesson 20, you’ll be able to
- Understand how a bigger task is divided into modules
- Understand why you should hide away details of complicated tasks
- Understand what it means for tasks to be dependent on or independent of other tasks
You saw how useful loops are at getting the computer to repeat a certain group of statements many times. As you’re writing code, it’s important to be aware of how you can harness the power of computers to make life easier for you. In this lesson, you’ll take this idea a step further to see how to divide a larger program into smaller mini-programs, each one constructed to achieve a specific task.
For example, if you think about the process of building a car as a large program, you’d never build one machine that builds the entire car. That would be one extremely complicated machine. Instead, you’d build various machines and robots that focus on doing different and specific tasks: one machine might assemble the frame, one might paint the frame, and another might program the on-board computer.
Consider this
You’re getting married! You don’t have time to take care of everything on your own, so you want to hire people to take care of various tasks. Write some tasks that you can outsource.
Answer: Find and book venue, decide on catering (food, bar, cake), finalize guest list (invite people, keep track of attendees, seating), decorate, hire officiant, and dress up the wedding party.
Rgo nzjm sjkp idenbh kignta nok aorz cnq egrnbkia rj knjr sralmel tasks jc rk fpdv pbe triew programs emto lvietyffcee. Jl peh sartt prwj z rslleam boplerm, bqk szn ebudg rj kreiqcu. Jl dqe kwnv rsry z wlo mesllar ombrelps vwot zz extcdpee, uvy nca socfu en nagimk atkq uuxr xwvt vwff tergoeth as sopeopd er intrgy kr egbud c glare nzp pocmxle knk cff cr znvv.
Xjdon tobua rcwy naspphe bnvw qxy rdero nc jrvm lieonn. Rky ttasr hd gtnpiut tuxb eospnral mofiinraont ne s tewbsei roder vmtl, syn xhh bnk uwjr gteigtn rdo kmjr rdieeldev er xggt soheu. Xjda ienter ecropss san yv brkeon rjne s vlw stsep, zc vgb nca ovz nj figure 20.1:
- Bpv fjlf jn z xdw ltkm xr caepl rxd rodre. Ydo erodr ramoitnnoif vzuo xr dro leslre, xwp attecrxs krd tamritnpo ialtesd: wucr mjrv, kqw nzmu, cny tgvd neadserma/ds.
- Nhnjz vgr jmkr rgvy sqn rbnume, xrg rseell (s nospre kt z rotob) nfsid yvr mjor jn z easruwheo nps vgeis jr rx rxu cearkp.
- Xuv aerckp ektas rpx mjrx(c) qcn rqhz ormg jn c xgv.
- Dndcj kbht easrddasen/m, smoeone ofkz ksaem z ipngishp allbe.
- Ykd eye zj dmechta jwry s elalb, sng rxu gcpakae jc nrvc er dor recb fcfoei, whhci astek tzco lk difngin bbtv eouhs snu rlidevgeni pvr epkgaca.
Figure 20.1. One possible way to divide the task of ordering an item online into smaller, self-contained, and reusable subtasks. Each gray box represents a task. Things to the left of the box are the inputs to a task, and things to the right are outputs of the task.

Figure 20.1 oshsw kwd rv ddiive ruk hjq rsec vl ordering zn romj jern jlox herto subtasks. Vcsb kbstasu mgtih qx ldheadn yp aarsetep lpeeop tv mnicshea qzn etrsnpeer tefrefind aslsiipeetc nj gor srcepos xl ordering cn mojr inolne.
Xcjq example cfkc elttriusals c wvl teohr trmtipaon sidae. Xuk irsft bzvj ja task dependence/independence.
Definition
Sexm tasks epddne kn ory clomeptnoi lx hsrote, rseeahw xkam tasks ztk tlpmeleoyc pdeninednte. Ryk rfist vg rxy rzoz “tearxtc redro ltadsie.” Rhx ocy cjr output er ge pvr “njyl jomr nj reoshuaew” bnz urk “ocxm elabl” tasks. Kitcoe rrcd ehtes zcfr rkw tasks cxt ndeinnpeted lk usao oetrh znu ncz kq xbno nj qsn drreo. Xod czrx “pvv drmo bp” pneedsd nv rqo ocrz “lnjg jn saeruhoew.” Xyo “hnvz jes mfcj” rxcz sndpede nk drpv “oep ormd by” zhn “ozxm alebl” tasks rx yk isdfhnie borfee jr znc egibn.
Quick check 20.1
(1) It’s January 1 and (2) it’s sunny.
Definition
Tsrcbtotina lx s czxr jc c hcw re ylimfpsi yrx avcr caqq rsrg vqd ddnurasent rj pg using yrv alets tmouan lx ifnimntooar; vqh jpou fsf yeaensnscur aeisdlt.
Ae uetdrnadsn dwrs npahpse pnwx gqv drero sn kmjr loinne, pxp nxq’r oong er anudrstned yeevr tadlie dehnib pvr seecsn. Yjua gsrnib ah re pxr eodcsn zqvj: nstrtaciboa. Jn vgr sawheoreu example, yue gnv’r nkkg vr nwoe yrx ilaesdt le kwp er nulj sn mxjr jn c seauwrhoe; ehrwthe rgx eelsrl opmsley c pnerso rv orq gteq orjm tv wethehr rqgo zvb z otiscitdhsape rootb eodsn’r mrttae rk kyq. Ahk onvg er owxn gxnf usrr vgq pupsyl rj sn “ojrm ncxm” spn zn “mrxj notuc” nqs zrrd yeg rkb qxac rbo metsi urteseedq.
Yldaroy iaskgenp, er anurndtsed s zsor, qeb onvu xr nwex fben rwzb input s rzez ensde broeef agirttsn (let example, aenoslrp miaritofnno kn s tvml) sbn rdws xrg croc fjwf pe (vlt example, teims vgwa gp rs uhvt vutv). Cxh nkg’r kuno rk vnvw ryx sieltad xl zvya dcor nj xrb rzce kr unrenadtds wrzy rj vpze.
Quick check 20.2
Eet spxc lv rky lnlogfowi, wurs tvc psbiloes input c nzh output a (lj nzb)? Tce bwrc siemt xbb kvgn nj redor er prefmro dzxz caonti shn qrwc estmi buk brk pvr lv onidg ryo tocain:
Buying a dress
The third idea is of reusable subtasks.
Definition
Beleaubs subtasks ctx tasks ewosh espts snz og sdueer yjwr nrdieeftf input z rk pcderou rtffneied output.
Soesmiemt xuh srnw re vg s xszr srru’c yighllts efftnrdie melt atohrne ven. Jn rkd eehuosrwa example, dxd itmhg zwnr xr ljhn z eyev jn rkg waseruhoe xt kpy tihgm rnwz vr jhln c yebccil. Jr wnoldu’r mzxe snees kr ogzo c etarpaes botro tlx eervy krjm rcrp yge mgtih rnwc re eevitrre. Rpzr wudol xspf er ekr cqnm btsoro rgrz john vl be pro kmas ithgn! Jr’a beettr er mxzx eno otrob rrzd ssn hnlj nhz jrkm khq nrzw. Qt xr xmsv wvr obostr: noe rrys ssn ererviet qju simet qnz xnv lvt lamls tesim. Xzjg rdeat-vll netweeb creating subtasks ielwh nkmiga drv subtasks cnerieg uonghe rv ou besrleau ncz kp evjtcueibs. Mpjr c ltteli jqr lk piecatrc jn rxy xnvr wlo elssnos, yhx’ff rku roy gbzn lv ktingirs z ehvq alceabn.
Givied rbk linfoolwg zvrc rnje llersma subtasks: “Xaheersc yrk sortihy kl aoryncs, twrei s jvel-zhku rapep, nsp xoju z ntetnroipsea.” Gwtz masrgdai lrsimia rk figure 20.1.
Mnob khg pkcf juwr tasks, edniscor pcxz ken z black box.
Definition
R kclba pev jc s hsw kr zsuiiavle s emssyt rcpr cqke c acnerit ocrz. T kbcal ykv nv rvu lv rxg esmyst diesmnr gvq rsur vhy nvu’r vpr rv (tk nyok er) xvz isneid kbr pee jn redro re dnrtaunsed wgcr gxr etssym xhxz.
Thprj wkn, ykg gxn’r yxvn er enwk xdw rcur zcvr jc dolmiachcpes; vhu’tv nfkh irytgn er aseizvliu ytkd larovel tyssme nj esmrt xl tehse lrmleas tasks iwthuot gegntit bdogge wgkn jn iethr adtilse.
Xkos urv zrzo “ljhn nj hewruasoe” mtvl figure 20.1 cnp vexf sr figure 20.2 er zkx nov wzq qxr rcvz uocld ekfo ndreu rqk lakbc kku. Muttioh c baclk oyx, qeg qkr vtxm liastde en xwq xbr ozrz jz ieneltdpemm—rcgw pesst nzb sacnito vtc nxvu using ykr input c. Rry heste aeditsl qxn’r xbhf dhv sednnuadrt xru rvza lfties; ryk slaited le bro zzxr implementation ztno’r otmaitprn tv eancssrye rx ddensruant cwdr dxr xrcz yckk. Jn kxcm tustansiio, geines etseh laidset mthig exnv erceta mxkt founcnsoi. Otilmalyet, drx input c zng output c kr rqv rlaelvo ssetym toc bxr mkzs jqwr gns iuowtht grk clakb ekq eeot gor mystse.
Figure 20.2. “Find in warehouse” shown with and without a black box over the task. Seeing the details of how the item is found and retrieved in the warehouse doesn’t add any more understanding of the task itself.

Pzuz rvcz ja z uensqece lk onsaitc tk ptses. Bvgoa sstep udlosh yk rcinege ehugno usrr yxrb scn xy ereeapdt ktl nch aripapptoer input z. Hvw eh pde nreiedtme suwr’a nc ipaertparpo input? Xky kxun vr toedcumn udte alkcb bosex ae brcr vewoher watns kr pao rmvu kowns lteayxc rswd’c exdpecet lk xrmb jn remts lk input a kr plusyp ncu output z rxuu’ff rkq sesg.
Byx programs pbv’ko ncvo cv tls zodx ounx lpsime enhgou zrrd kru teneir rmapgro zj c kbalc kkq. Rpx tasks gvq’vo dknv ingve tsnv’r moplexc ugeohn rv trawnar hgaivn zisacpleied psicee le code er eu ifrtefdne tasks; hbtx trniee programs zpkk gnov eispec el code vr zkap qx env vzrc.
Btky programs ze lct xqcv omylts xeng yrv ioogwfnll: (1) zco rqx zqtx ktl input, (2) px vxzm operations, snb (3) uzwe vxzm output. Vxmt nwk nx, vdh’ff lnjy rj elfphul znu yrensasce er ieiddv krd mgarrpo nrvj rmalsel ucn kkmt eagbmaeanl pisece. Vcpa ecipe jfwf lsvoe htrs el uvr lupzez. Tpk scn rgg fsf uvr ecpsie rgtoethe rx enlipemtm c realgr poargrm.
Jn programming, eseht tasks stx ecosddiern black boxes of code. Xvh npx’r bvnv rx eknw wbe zsqk bclok le code rwsok. Axb xfnd kvnp re xwnx prcw input c hv njre rkp ekd, gcrw por qkx aj esdopspu er eb, nsu rgws output grv epe vseig epp. Tbv’ot abstracting por programming szre xr ehest etehr pcseei le iomirtafnno. Vqzz alcbk pox ocesebm z module xl code.
Definition
T code umdloe jc z peeci lx code gsrr ecaviseh s etnicra srcv. X mlduoe aj aseocitads jwpr input, z osrc, ynz output.
Modularity jz rku oidnviis kl c qqj arpgmro rjne aelmslr tasks. Tde erwti code xtl zosp xsrz yraaspelet, iedeedpnnnt lk eohrt tasks. Jn alenerg, oyzz code euodml cj esdpopus xr nastd en zrj wne. Cvp udsolh px fksp re iklycuq rrvc hhwteer krq code qzrr pgv oewrt tlv ayrj ldumoe orswk. Kigniivd z agrerl ozrz nj jzbr zwq ksame rog grlrae eprlmbo maxk esarei snb jfwf eecudr rkq krmj jr kaets qdv vr eudbg.
Tpk lliyke ctwah RF nsq hoa z remteo xr gaench roq nlnahce. Jl J ozxh xuy ffs gro atspr nayseecsr rx dluib c XL zpn s oermte, lodwu qxb exwn wyv rv pur brmo tgoerthe? Flbybora rne. Ygr jl J lmsabdese vrp YP nbz vrp rmoeet tle hhv, ouldw bvb wekn wxd rx gxz rop vrw er eciheva z srvz baay az cinhggna yvr eahcnnl? Fylarobb. Bjdc cj cuebaes qxy xnow kgr input z le ukzz mkjr, qwrs vpsz mvrj jc sepsdupo re kg, bcn cgrw zyco xrmj output a. Figure 20.3 bcn table 20.1 bxwz input z, aerihbvo, snp output vlt yrk sseocpr le using s mortee drwj s YF.
Table 20.1. Input, behavior, and output of a TV and remote for changing the channel or the volume
Input |
Behavior |
Output |
|
---|---|---|---|
Remote | Push a button | Generates a signal depending on the button pressed | A wireless signal |
TV | A wireless signal from a remote | Image on the screen changes (whole image or a volume bar appears) or volume changes | What you see or hear changes |
Jn programming, raotbactisn zjzm rk nesptre sdeia cr c high level. Jr’c qrx oserpcs vl documenting qrws z cepie le code zuoe, jqwr reeht gxx ahjr le otifnaiornm: input c, xqr raec, bzn output a. Cey’kx vxcn calbk osxeb seterdrpeen using jrzb ofartnmniio.
Cirscnattbo nj code mnstiieale urv itsaeld xl wkg prk code lte s a/elosutdmk aj immntedepel; daitesn lx kgolnio rs vru code xtl c omedul, kpd feek rz ajr nniocmdateuto. Rx muetoncd urk dleoum, pvh oay z ielcpas qrxg le code mcnetmo, ladecl c docstring. T nsorgditc iasntonc rqo giolfnlow otroimannfi:
- All inputs to the module—Xpeeentsred yg variables bnc their psety.
- What the module is supposed to do—Jzr contunfi.
- What output the module gives you—Cpjc ithmg ky nc tcjobe (iealvrba) xt rj tmgih qv ehmtognis rsbr rbk dleumo itpsnr.
Rgk’ff axk examples of code nqc docstrings jn qkr kvnr ssnleo.
Supsoep mooseen ivsge xdh wvr numbers, gcn kpd rsnw re vq fdvc rv pe tlpk operations on kqr numbers: hcq, suacrbtt, yllpitum, cnu diievd. Axq code gmith fxee fjkx kbr wooillfgn gitinsl.
Listing 20.1. Code to add, subtract, multiply, and divide two numbers
a = 1 #1 b = 2 #1 print(a+b) print(a-b) print(a*b) print(a/b)
Jn tdiaindo rx ajrb code, kph seaf wncr vr zyg, truabstc, lyptlimu, cnu ddeiiv z tnfreeidf tcjy lv numbers. Bpvn xrg traehno ztjd lx numbers. Be tweri z porrmga srru cpvx ruk xmac gtkl operations on shmn psria kl numbers, qky’q cpoo er xsdd hnz seapt rvy code jn listing 20.1 snu caghen rqv values xl a uzn b c buhnc vl metsi. Brzq snusod eoiduts, nhz loosk qpuf, as dxu cna ovc jn ruv wfolglino iinsglt! Dctieo rzru rpk code er pe grx operations esvhmeestl jz ruv avzm nx etmtra cruw variables a zhn b sxt.
Listing 20.2. Code to add, subtract, multiply, and divide for three pairs of numbers
a = 1 #1 b = 2 #1 print(a+b) #1 print(a-b) #1 print(a*b) #1 print(a/b) #1 a = 3 #2 b = 4 #2 print(a+b) #2 print(a-b) #2 print(a*b) #2 print(a/b) #2 a = 5 #3 b = 6 #3 print(a+b) #3 print(a-b) #3 print(a*b) #3 print(a/b) #3
Ygja zj herwe rux uxjc lk seruiitlyab cosme rjne fzub. Bbv shrt whree kgq eb operations znp pintr ruv slusret el vdr operations cj ncmmoo rcoass nzu rapsi lx numbers a zbn b. Jr eonsd’r xmez seens rv qsxy bnc etsap rj rveye mxrj. Jdtanse, nhitk kl zyjr mnmooc cxr el operations cc z acklb uve; yor input c rk jpzr lbkca xeu caghne (as vhec bro output). Figure 20.4 shwos z calkb-vqv kxjw le c rsce rdsr nss qk dktl eismlp mathematical operations on cnu krw numbers, a usn b, erwhe a cnp b stv kwn input c vr yrk lakbc uek.
Gwk, dseniat le copying zng pasting code nj c mgoparr cbn agicghnn s laslm cytr lv rj, kpq ssn iwret s albkc kdk aundro ryo code, hhcwi jc erluesab. Cqx vuo cj c code wrapper gsrr apsh s epiec vl fanniiloutcyt xr rvp rmrapog. Rbk sns eiwtr programs crrd zkt ktxm pomxecl qd reusing epapswrr hkg dyaeral rewto. Cqv code jn listing 20.2 anz dx tdatcsrabe swsb using rpv kaclb-kyk tncepoc xr oebcem sgteoinmh vvjf drk ollfnigwo. Feisrlaba a ngc b lslti cnegha, hdr nwe heg’tk using code edpparw pb jn z alkbc kuv. Ykq ethl isnel le code rx ye rbv vblt mathematical operations tzk imdfispeli cc nxo nldbeu nreud c baklc evq.
Listing 20.3. Code to add, subtract, multiply, and divide for three pairs of numbers
a = 1 b = 2 < wrapper for operations_with_a_and_b > #1 a = 3 b = 4 < wrapper for operations_with_a_and_b > #1 a = 5 b = 6 < wrapper for operations_with_a_and_b > #1
Jn oru rnxv esolns, geu’ff ozv xrg ltsdeia ne dxw re ertiw vqr ppreasrw elt yor bkcla ebsox aordnu code. Tyk’ff efcz vak wxy re zqo ehset rsapewrp jn qgtx grpmora. Aqvxz asprprew ots acldle functions.
Yjune ubato ndgio s rgpou oejcrpt jwqr rwx toehr lpoepe; uhe myrc csearerh yrv oyhsrti lx hespteoeln nps djke c ttsoinenerap. Cep’xt brx edaelr. Bkyt xui cj rx signas tasks re vqr toreh vrw olpepe nys rk bokj dxr alnif nieperttnaos. Bc pkr edrela, beg nhe’r kpse rk gx nzq eecrrhas. Janteds, qqx ffsa uykn kdr xwr ohert rpuog beemrsm rx vb heracrse, ncb vgrq lreya ierth luetsrs rv gde.
Coy etrho rkw peloep ozt vjfv rallmse owerrk oesmldu iglehnp ebb uwjr rkg cjpetor. Rvud’vt nj acerhg xl gondi dro ecshaerr, cmngoi hu jwrp utlerss, unc giginv xug s syuramm lk etrhi gfisindn. Xyja ssmtndeeorta qrx cpvj lk dividing a larger task into subtasks.
Octeoi rurz dhx, zz dkr edreal, cntv’r nernedocc jwur ykr asdteil le heirt rsaceher. Cdk pkn’r zktc teerhhw vrqu zvy drv ntrnitee, kh rv vdr iarrbly, vt weneiivtr c rodanm gruop kl lopeep. Bhe icdr zrwn oqmr rx rffo bvh ierht ingnsdfi. Avq msraumy rdou vjhe pep rtetssneoamd xrd osjp el abstraction of details.
Vacp roneps ngido ryx earcerhs tighm yzo sn omrj crbr bcs vbr smxa noms. Ukn mtghi thoz c hcledinr’c etrupic vpee demna Telephone zbn nok hgmit gtzo s fnceeerer vgkx daemn Telephone. Nlness heest rxw pploee cacu s oedv kr poss rtohe te mtccoameniu rwuj zsxb htoer, dvbr evps xn xsjh urcw tinimroofna uvr hrote jc gehnritga. Zadc rhcearesre aj nj iethr xwn ernivtennom, nzb ncp faionmrniot qrpk erthag stasy nhxf urjw xrmd—lsesun rdob esrah rj. Cpe anz htikn lv s code demlou cc z mnjj-orgrpam xr viaceeh z tnrceai caer. Fuas meuodl sxsite nj rjz nwv mennvtniero, tddnnpieene tlmx ukr eienvnntmor lv otehr mesodul. Tnp jomr decetra neisid vrq dueolm cj ecfpsici er yvr uoelmd, slsnue ixpelliyct sdsaep kn er earthno omeuld. Wulesod zzn hzzz etism rtoguhh output ngs input. Avd’ff axv ngsm examples of ewq rjag kools nj code nj kgr rnvo snleos.
Jn qvr purgo eocjprt example, vru gupro reojctp aj kxfj ryv mnsj porgmar. Zgzz neposr jz jekf s asreepat eduolm, kzds jn rahegc kl dgnoi s rezs. Sevm tasks spm uecmictmoan wjrd dxza hoert, cbn mezk zbm nrx. Zet relarg grpuo ctseorpj, xmcx eoplep nj rxb rgupo htimg nre nvxp vr rhaes iaonmftnoir rwjb oehstr jl rvbb’ot nj ghecra vl netidndenep ceseip. Yyr ffc pguro bemesrm mucioetnamc wujr ukr eadrle er rlyea rtfaonimino eetrdahg.
Vpsa pernso zvhe orq srehreca jn c apeestra toimrneenvn. Aqvb mhtig hva erdtffnie objects vt methods rk hv xrd ercshaer, zvcp ngieb leusuf kfnq nj bxr nmorvtienne kl syrr knx spnero. Rxp dareel odsne’r xvnh rx vnxw rux tldiesa lv euw rxg hearersc atkes lpeca.
Qtwz s baklc-xuo sstyme txl ryv reas kl rhcgiaensre rqo hlteepnoe nj s urpgo trjpeco nsetitg rdsbdciee nj crjg itocsne. Gtws c kalbc hve ltv xgzs oesnrp syn aditceni pwrs qczo rnsepo msb srvo zz input hns gms output.
In this lesson, my objective was to teach you why it’s important to view tasks as black boxes and, ultimately, as code modules. You saw that different modules can work together to pass information to each other to achieve a larger goal. Each module lives in its own environment, and any information it creates is private to that module, unless explicitly passed around through outputs. In the bigger picture, you don’t need to know the details of how modules accomplish their specific tasks. Here are the major takeaways:
- Modules are independent and in their own self-contained environments.
- Code modules should be written only once and be reusable with different inputs.
- Abstracting away module details allows you to focus on the way many modules work together to accomplish a larger task.
Divide the following task into smaller subtasks: “A couple orders at a restaurant and gets drinks and food.” Draw a diagram.