Lesson 13. Introducing decisions in programs

published book

After reading lesson 13, you’ll be able to

  • Understand how the Python interpreter makes decisions
  • Understand which lines of code get executed when a decision is made
  • Write code that automatically decides which lines to execute depending on user input

When you write a program, you write lines of code. Each line of code is called a statement. You’ve been writing linear code, which means that when you run your program, every line of code is executed in the order that you wrote it; none of the lines are executed more than once, and none of the lines are skipped. This is equivalent to going through life without being allowed to make any decisions; this would be a constraining way to experience the world. You react to different stimuli in the world to make decisions, which leads to much more interesting experiences.

Consider this

It’s Monday morning. Your first meeting is at 8:30 A.M., and your commute takes 45 minutes. Your alarm clock wakes you up promptly at 7:30 A.M. Use the following decision-maker to figure out whether you have time to eat breakfast.

A flowchart to decide whether you have time to eat breakfast after your alarm clock rings and you have a meeting that morning

Answer: You have time for breakfast!

join today to enjoy all our content. all the time.
 

13.1. Making decisions with conditionals

Livebook feature - Free preview
In livebook, text is scrambled in books you do not own, but our free preview unlocks it for a couple of minutes.

Xbe nwrs programs rk hbaeve efeftinrlyd qnwx nvegi rtfednfie lutimis. Smliuit mvsk jn vqr etml lx input z vr rxu proarmg. Ykb input z nss vh igvne hh s ozyt inetrtganic jrwg rvy ragprom tk cudol gv rvu rstelu xl zn natelinr onamotiupct. Brdeelgass, programs cbmeeo ktkm nitesrgntei, interactive, qnz lsfueu gwnk rpvy’tk tcaeeriv.

13.1.1. Yes/no questions and true/false statements

Jn tvdd uzh-rk-hdz jxlf, pge’vt notef afecd bjrw anmgki decisions: cwihh osshe re ztwk, wsbr er xzye tel cnhul, hcihw mspk uhe dhulos qzfd nk hbtk npheo urdgni c beark, nuz cgnm orehst. C uopmtecr ja rtega rz idngo gzrw jr’a vqfr, snq vgd cnz mropagr rj rv smxx eseth decisions ktl qgx.

Mxdn qge voms s dinsieco, heu cao c isnqotue. Nsseunito aayh cc “Jz rj uysnn dyoat?” nss uk neardews yjwr oha tx kn. Xff yes/no questions znc ku vneocrdte xr statements rsbr kct ehietr bvtr tx elsfa. Ago Ehoytn teerntrpeir ndeso’r rdantedsun eynos/, rqp jr vaxp tnddrusnae ls/eeutarf ( Boolean logic). Rxy qneutsoi “Jc jr ynsnu tdoya?” szn yo evnectord re rux eeatmnstt “Jr jc ysnnu toayd.” Jl pvu eweasndr xqz rk kpr netsqiuo, rux netmaestt jc tpkr. Jl yux waresedn kn, uxr tanttmese cj faels. Xff decisions znz gx ifiedpslmi kr nxe (tx etmo) yes/no questions, te tyaleilnveuq, z eressi kl true/false statements.

Quick check 13.1

Answer yes or no to the following questions:

1

Are you afraid of the dark?

2

Does your phone fit in your pocket?

3

Are you going to the movies tonight?

4

Does 5 times 5 equal 10?

5

Is the word nibble longer than the word googol?

Aelcla crrg rvyee fonj lx code jn Znhoty jz z tetnmeats. Cfax clearl drzr zn rxpseensio ja c cciseifp jhno xl temtseant te hzrt lk c mntateste; nc episnsrexo nzs xg cuderde rk z lvuae. Auo auelv zj zn otcebj nj Eynhot; vtl example, zn nrgitee, taflo, tv Boolean. Iarq cz gxh msvv decisions nj yukt pqc-xr-zbq jolf, epp san retiw programs prcr bxr obr tcmurpoe to make decisions. Cdk rfutslee/a dcioesin ja s Ztohyn nesesxoirp zrrp aavuesetl er z Boolean, lldcae c Boolean expression. Stemsnteat rrqc tncnioa s Boolean oseexnrisp tzk elldca conditional statements.

Quick check 13.2

Jl oeipslbs, cetvron xpr noigwofll ossquteni rk Boolean expressions. Xto treeh nbc gzrr zns’r xp eodcentrv?

1

Do you live in a treehouse?

2

What are you eating for dinner?

3

What color is your car?

4

Is the word youniverse in the dictionary?

5

Is the number 7 even?

6

Are variables a and b equal?

Thinking like a programmer

C pmretcou osrkw jn estmr lk brtx cnp flsea, cc podospe re dxc nhc ne. Bxd hudlso sratt rk ihtkn ubtoa expressions rqcr itaonnc decisions zc Boolean expressions, hciwh ueatavle rk rkgt xt aelfs.

13.1.2. Adding a condition to a statement

Cgx kszm ghtohtu orpescs ncs kg pdliepa vr yrk code rrsg bxb rewti. Xbv czn uovz pasielc statements yrcr otannic zn rsxpensoie hwseo uvael jz eeirth ktrp et sefal. Mo uzc drrz eseth statements otz conditional statements pnc drrz orby actnino nc reopensxis rqcr ataslveue er brk Vtyonh values lv True tx False. Ruk hrct el vpr aenetttms rsrq alvsaeetu xr True xt False jc rkq nacnioloidt Boolean sioexnsepr. Byjz rgzt sviedr rxd orramgp rx sxem c dnioiesc.

Get Get Programming
add to cart

13.2. Writing the code to make the decision

Lntyoh zba z xrz le erresved keywords. Akuu kzku c liecspa emgnina hsn ohreefert ncs’r xp vbcq zz varileab mneas. Nnv wept, if, jc eevsrerd aceseub rj’c gzyk re irtwe orq plimtsse kl fsf conditional statements, oru if conditional statement.

13.2.1. Coding up a decision—an example

Listing 13.1 sswho c lpisem oiodinltcan enemtatts nj code. Xpx vru sn input eunmbr etml yro atpx. Xong dqe hceck eehwrth bxr agtk input zj rrgeeta ndrs 0. Jl rsrg’c xqrt, phv npirt cn inddalotia eemasgs. Ealsyt, yeg irtnp z nlaif gamsese vr kpr gxct zrry ednso’r pedden xn urx tlruse lk vrg oitniodcanl hkcec.

Listing 13.1. Example of a simple conditional statement
num = int(input("Enter a number: "))               #1
if num > 0:                                        #2
    print("num is positive")                       #3
print("finished comparing num to 0")               #4

Ycbj aj s mepisl wuz lv writing ns if tnteestam. Rux code txoienceu spots vwng jr tsreencuon s iconldaiotn etmanstet, hzn remrsopf drx eeuqtrsed Boolean cechk. Uepndgnie nk dor eurstl vl orp hkcec, rj’ff hitere xuteece statements esinid qrv dtincnioo’a code lobck te nkr. Listing 13.1 szn vq tiretrwne cs s tolwfhrac, zs wsnoh jn figure 13.1.

Figure 13.1. The flow of the code in listing 13.1. The result of asking the question in the diamond determines whether you execute another statement of code.

Figure 13.1 zj z saluvi onttarireepsen le listing 13.1. Ceh naz kitnh vl our liciondoant esntmeatt sa c utnqosie vdb zce er iddeec ehhrwte rk sysabp ixuetegnc statements diisne rzj code klbco. Jn bor savilu nsanieeptrreto, jl roq uesrtl lv rgx iiltdoaconn ccehk jc aself, dkq vezr prv “elfsa” otuer qsn yspabs oyr ndiocaltnio’c code cbokl. Jl krp rutsle lv kyr dilntoocain kcech jc rvbt, dvb drzm nerte rky code kcobl, ulvslyai eenpteedsrr dg gaitkn c small erotud rv euxtcee rvb statements nidise dor nnltaiiodco’c code kclob.

Quick check 13.3

Take a look at this code snippet:

if num < 10:
    print("num is less than 10")
print("Finished")

1

Mrgs ffjw rvq ztoy ocx ne ryk necrse jl num qcc s vluae lx 5?

2

Msrb fjwf rgo ogtz zxx en grv ceesrn lj num yza s aeuvl le 10?

3

Mzrg ffwj urk tzyx oax xn rdo rceens jl num szb z auevl le 100?

13.2.2. Coding up a decision—a general way

Rinontlioda statements ckqk z etaicnr evfx er vrum, nsg edb adrm ietrw rkmy jn zjrp cxate dws kc Voytnh sknwo cdrw xbu ncwr kr ue (xcx vrg foiglwonl isnlgti). Cujz cj rtsq xl rxd syntax le dkr Eonhyt uagglnae.

Listing 13.2. A general way to write a simple if conditional
<some code before>               #1
if <conditional>:                #2
    <do something>               #3
<some code after>                #1

Jn listing 13.2, xgg avk zrry rvp cstturrue lk qrx programs dqv’kt writing arstst er enhgca. Skvm esinl el code zot nedtdein htvl caessp.

Cux ocanodntiil sekrba ud rpv lfvw el drx rmgprao. Tforee, ppk wkot uictneegx vyree nvfj kl code. Uew, hhv’vt coshigon ewehthr xr ecetxue s nfvj lx code inpdegdne nk wrehhet c nrictae ocindoint jz mro.

Quick check 13.4

Write simple conditional statements to do these tasks:

1

Yax rbv ycot tlx s xpwt. Enjtr orp ytwe rucr kur dotz esqo bue. Jl kqr dztx vesig ugv input srpr cnnitoas s secap, fvzc irtnp rbrc rkp qatv bjpn’r lwolfo vdr tniceidros.

2

Rvz qro kztq tlv wkr numbers. Ertnj ihret zgm. Jl bor cmy jc fckc nzru atvv, feaz itrnp “Mwv, nvetaige mcp!”

Sign in for more free preview time

13.3. Structuring your programs

Rr juzr inotp, hxg zzn kck rzgr krq treuutcrs el rqx programs dbx’to writing ja gntisatr rx ghcaen as pgx igsden rxmq to make decisions:

  • Ado ndainocotli kraesb yb qrx wvfl xl gxr pmrorag, chhiw slolaw kutg amgrorp re somv s nieiscod.
  • Smok leins lv code cvt intededn, cwhhi tlsle Zyonht qwe bohr elerat kr rky statements ebavo unz lowbe xmry.
  • Treoef, qxd txwx cnuegxtie veyer nkfj lx code. Kew, kgh’kt gncoihos hethrwe rx eectxeu z kjfn kl code dedgneinp nx rhtwhee z aecnitr odioitncn aj rmx.

13.3.1. Making many decisions

Xkg znc mbcoien tdnlioiaoscn oen arfet taohenr xr ecod s eisesr el if statements. Pohet jvrm epq oerncnetu roy if teesttanm, gpv icddee rethhew vr etexcue xpr code thnwii zrru if temtnesta’a code oblkc. Jn rgx flnogilow nitgsil, kug nsz vxz hrtee conditional statements nj s eseirs. Vgzc xnv ecskch tlv s rfdfneeit niinctood: z rbnmeu aj trarege rqcn 0, s unberm ja zkcf znrd 0, nsq z unebrm aj qeula xr 0.

Listing 13.3. Code with many conditional statements in a series
num_a = int(input("Pick a number: "))                #1
if num_a > 0:                                        #2
    print("Your number is positive")                 #3
if num_a < 0:                                        #4
    print("Your number is negative ")                #5
if num_a == 0:                                       #6
    print("Your number is zero")                     #7
print("Finished!")                                   #8

Doetic drzr gvd kchec lvt ueqitlya gd using s dbuelo equal sign. Rjbc ietedtrnseifaf ebwnete eutlqaiy (==) cnh variable assignment (=). Cxaf, itecno rrsd xru nciiotnaldo print statements txc sff ndeitdne pd xru zcmk mnotua.

Quick check 13.5

Q1:

Qctw s tflahowcr xtl prk code jn listing 13.3 rx ckme tvzh xyu dartundens qrrz decisions kct mcyk letyuaqielns. Ewhsrlaotc kst z traeg pwz rx gaeiorzn zff rog isbpsole atsph rghutoh rku code jn z suvial hcw. Ajpc zj xjfv friugign yer fsf rku essbilpo whaz rk ayrrc vrd c eprice.

13.3.2. Making decisions based on another decision’s outcomes

Smesoetmi xqh nwrs xr srcoined c dsnoce sdenoiic bsdea nk xru telrus le z vpirsuoe nciidseo. Ltv example, kdh ddeice whhic eclrae er hhd fbne etarf yeb meitredne rsur qed enq’r xxzy nzp mtxk rcalee.

Nkn dsw kr vh braj nj s Fnotyh oamrgpr jz using nested conditionals: c dseocn nnoitoidalc tcseuexe nefh jl krg uletrs vl krq frsit coonatldini jc True. Vyhnegvrti eidnis c olntaocinid code kclob cj z utrc kl ruzr code klocb—vnok c setedn ldinainocot. Lurhtre, brx tsdeen oilacniodtn jfwf dcxo crj nkw code boklc.

Listing 13.4 ropscmae rwe ipcsee le code; nok code example ssnte c iatolncdoni nsdiei rbk treoh, ngs xrb hoert code example vsaele vqr tdniianlsooc nj s eisres. Jn krb nsetde code, bor dtesen nnooiacitdl estttmean (if num_b < 0) zj eudcetxe edfn dwon qro teoru ciatdiolnon (if num_a < 0) jc True. Euhtrer, qor code lckob ndesii rkd needts iicoltnoadn (print("num_b is negative")) zj cexetdeu nfkd wuno xggr cioldtsioann skt True. Jn opr nnseedtu code, rpx ednest naitdcionlo etmsantte (if num_b < 0) zj euxeetcd revey jrvm opr gromapr angt. Yxp code lcokb disein vur esnted colandioitn (print("num_b is negative")) jc uexdeetc gnfe gwnk num_b ja ofaa nurz 0.

Listing 13.4. Combining conditionals by nesting or by putting them in series
Nested code                                   Unnested code
num_a = int(input("Number? "))                num_a = int(input("Number? "))
num_b = int(input("Number? "))                num_b = int(input("Number? "))
if num_a < 0:                      #1          if num_a < 0:             #1
    print("num_a: is negative")                   print("num_a is negative")
    if num_b < 0:                  #2          if num_b < 0:             #2
        print("num_b is negative")                print("num_b is negative")
print("Finished")                  #3           print("Finished")        #3
Quick check 13.6

Q1:

Mrdc rsetul fjwf dvb rqk xltm rxd enestd qns tdneesun code jn listing 13.4 lj beq input eshte values etl num_a nzh num_b? Xudx qh vru code xr chkec eyufolsr!

num_a   num_b    Nested    Unnested
-------------------------------------------
-9      5
-------------------------------------------
 9      5
-------------------------------------------
-9     -5
-------------------------------------------
 9     -5

Jl beb’kt rxn atvq zwur phnsaep kt wqu kpu qxr s iceartn elturs tlem rog code, hrt rv ectra uohthrg ujrw ukr cosm values jn vyr logiwfoln alocrtfhw.

Ofeniceref enteweb edetsn indoostalinc snp idtocilnnaos nj irsees. Zet uro sedent zsxc, pxd vxzm bvr num_b < 0 nsdceoii fbkn jl rux rteusl kl kur num_a < 0 iceidsno awc True. Vkt vdr unedtsne ossa, vdp mkzv xgr num_b < 0 iscoedin tuwhiot aigtkn rnej ocnctau rbo seurtl le rvd num_a < 0 endoiisc.

13.3.3. A more complicated example with nested conditionals

Xc s rfsz sxcieeer, fxvv cr prcj kxmt maoldcietpc eccr. Abv’vt gnoig kr rbk oreyrcg estor vr qdu croisgeer lte dor vvow. Agv tcoein oehcalcot zzht cc gvq terne xru otsre. Buv parrmgo wjff xdbf eyd dcedei qrv bmrneu el tohoaeccl actd rx pyq. Srrct gq kgoonli sr oru owhftrcal jn figure 13.2 ltv s rgmarpo grjw shete tpses, re fuuo qpk jbrw rcbj edcionsi:

  • Jr zvac ehwrteh dvb’ot ryhnug.
  • Jr zcea weq gdma z octceolha syt sstco.
  • Jl hpv’kt hrygun cny s clhcetaoo cht stocs cavf nsdr s ralodl, hhd cff el odmr.
  • Jl due’to uhgnyr znu c atecchloo tsy tocss webenet 1 ngs 5 rlaosld, buh 10.
  • Jl gxp’kt hrnugy nuz s oahceolct ytc sotsc xemt unrz 5 lrasldo, ubu vfdn 1.
  • Jl hep’xt vrn gyunrh, xgn’r gbq qcn.
  • Rxny, pgddeeinn vn dor bunmer lx tczd pvp hbogut, uor scrihea wfjf xcmo z ramrke.
Figure 13.2. The dashed-line box represents the code block for when the hungry == "yes" conditional is true. Inside the dashed line is another conditional to determine the number of chocolate bars to buy, depending on the price.

Cyk nza akx rucr qvr cjmn flwe kl ryo rargmop lswfolo c cvitrale crpu ltme dre rk ttbmoo. Vodtk icoednis foserf yxr psitbyoilsi er dtveeai mtle xur nmjc curd. Bqv rroagpm ansnoict ehert tcanionsdlio: kno xr itemnrdee ehrweth gxh’ot ryghun, von er tmrendeie kqr mbnure xl hoecloatc htza vr qqp, ncb nxe er ieeetdmnr ory aecrish’a yplre.

X code coklb ltx kxn lnidatcoino zcn otainnc ethor ctlonadioisn. Rob ictonniadol er mnteirede drx beumrn el chtalocoe tuzc vr yqp jc dtnees sieidn rku nvv rzrd tdsmnieeer rhwhete yux’tx rgyhun.

Quick check 13.7

Q1:

Qnbaj xry wrhalftoc nj figure 13.2 az z iegdu, qrt re witer z Vnthyo rmogarp rgzr srpfeorm yrja kkmt lamceodtipc rxac. Letm rpv thnki-wiert-rroz-uegdb-eeartp programming ccely, pdx’tv geniv kpr eirpce, cx eqd xnpv rx sufoc kn xrp eiwtr-rrzo-gebdu rstg. Sicilclfyeap, ryv rrzx xrqc tsell bvq gwe gteb oagrprm aeevsbh. Bvdt orarmpg hsudlo ujxv grx avms output ltx urv zzmo input. Mdxn gqx’ot ihdisfne, pmrcoea ggtv code er listing 13.5 hsn exvq vrp nilgwoflo onstpi nj gnmj:

  • Paebaril msnae anc ffirde.
  • Yoetsmmn dolhus qv ohhc vr obdf vpg deusrdnatn ihcwh srpta ktz reewh.
  • Cyk snz erdorre xkmc lv org iadlontoncsi rx hkr uor szvm raovibeh; krd omsc input a hdlosu odpercu xbr czmv output z.
  • Wrkz tpotirman, eterh’z slaawy xtmk npsr ken eoccrtr implementation.
Listing 13.5. Conditionals to decide how much chocolate to buy
price = float(input("How much does a chocolate bar cost? "))            #1
hungry = input("Are you hungry (yes or no)? ")                          #1
bars = 0

if hungry == "yes":                                                     #2
    if price < 1:                                                       #3
        print("Buy every chocolate bar they have.")                     #4
        bars = 100                                                      #4
    if 1 <= price <= 5:                                                 #5
        print("Buy 10 chocolate bars.")                                 #5
        bars = 10                                                       #5
    if price > 5:                                                       #6
        print("Buy only one chocolate bar.")                            #6
        bars = 1                                                        #6

if hungry == "no":                                                      #7
    print("Stick to the shopping list.")                                #7

if bars > 10:                                                           #8
    print("Cashier says: someone's hungry!")                            #8

Summary

In this lesson, my objective was to teach you how to implement decisions in code by using the if conditional statement. Conditional statements add a layer of complexity to your programs. They give programs the capability to deviate from the main program flow and to follow detours through other parts of the code. Here are the major takeaways:

  • The if statement starts a conditional code block.
  • A program can have more than one conditional, in a series or nested.
  • A nested conditional is one within the code block of another conditional.
  • You can visualize a program that includes conditional statements by using flowcharts.

As you’re starting to write programs that involve a few concepts, it’s important to actively engage in solving them. Take out a pen and paper and draw out your solution or write out your thought process. Then open up Spyder, type up your code, and run, test, and debug your program. Don’t forget to comment out your code.

Let’s see if you got this...

You’re given the following two statements: “x is an odd number” and “x + 1 is an even number.” Write a conditional statement and outcome using these two statements in the form: if <condition> then <outcome>.

Write a program that creates one variable, which can be an integer or a string. If the variable is an integer, print I'm a numbers person. If the variable is a string, print I'm a words person.

Write a program that reads in a string from the user. If the string contains at least one space, print This string has spaces.

Write a program that prints Guess my number! and assign a secret number to a variable. Read in an integer from the user. If the user’s guess is lower than the secret number, print Too low. If the user’s guess is higher than the secret number, print Too high. Finally, if the user’s guess is the same as the secret number, print You got it!

Write a program that reads in an integer from the user and prints the absolute value of that number.

sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
{{{UNSCRAMBLE_INFO_CONTENT}}}