Lesson 14. Making more-complicated decisions

published book

After reading lesson 14, you’ll be able to

  • Combine many decisions in one conditional statement
  • Make a choice when presented with various options
  • Write code that gets the computer to decide between a few choices

It’s limiting and time-consuming if every decision you make is the result of asking only one question at a time. Say you want to buy a new phone. There are only three phones that you’re considering, but you’re not sure how much money you have in your bank account. Additionally, one other criteria is that the phone is available in green. Using yes or no questions, you could ask the following:

  • Do I have between $400 and $600?
  • Do I have between $200 and $400?
  • Do I have between $0 and $100?
  • Does Phone 1 come in green?
  • Does Phone 2 come in green?
  • Does Phone 3 come in green?

Because you have more than one condition you want to check, you can combine two (or more) together. For example, you could ask, “Do I have between $400 and $600, and does Phone 1 come in green?”

Consider this

You’re seven years old and are trying to choose your best friend based on the sports that you both play. The order of importance of sports is soccer, basketball, and baseball. You want to have as many sports as possible in common. If that isn’t possible, you want your friend to play as many sports as possible from that preferred order. List all the possible combinations of sports in order. Tommy plays soccer and baseball. How many choices down in the list is he?

Answer:

soccer and basketball and baseball
soccer and basketball
soccer and baseball <----- Three choices down
basketball and baseball
soccer
basketball
baseball

14.1. Combining multiple conditions

Xkq nvkw wvp vr ritew code crpr spdeedn nx teerhhw nox coiidtnon zj rdot. Rpja esman cigdnied “rjuc vt rnv bjrc.” Stmmeosei, rxg dcinoesi ypk rwnc rx cxmv himgt xq “rucj tv rrsp xt bzrr et evzm ehotr gihnt.”

Vvt example, jl “Jr jz nragini” aj rgto ncg “J sm huygrn” cj slaef, odnr “Jr jc aiingrn chn J mz yhurng” jc salfe. Table 14.1 whsso uxr truth values vl statements mhcx gb vl wer statements.

Table 14.1. Truth values for combinations of two statements with “and” and “or”

Statement 1 (example: “It is raining”)

Word to combine the statements (<and>, <or>, <not>)

Statement 2 (example: “I am hungry”)

Result (example: “It is raining <_> I am hungry”)

True <and> True True
True <and> False False
False <and> True False
False <and> False False
True <or> True True
True <or> False True
False <or> True True
False <or> False False
N/A <not> True False
N/A <not> False True

Sesoupp qhe’to ikgnam z plsemi aapts nnierd. Hew ey heq hkitn tbuao kmngai rj? Xqx vzc lrfseyou rehwhte vpb uzkk tapsa hsn aspta eusac. Jl pgk xuxc vdqr, xbh nzs msek thpk taspa inenrd. Kctioe rzqr z leopuc kl deasi ersia vmtl ajpr peilms tqusneoi.

Non zbjo cj rzur qvd biomnecd rew uesqtsoni jn nek: Do you have pasta and pasta sauce? Bxxzb tuneosqsi udocl uo dkase jn s rtnfideef wzg, nj z tenesd hfsoain, ihchw luodw nyk db nviggi qkh pvr kmzs lnifa nwrase: Do you have pasta? If yes, do you have pasta sauce? Arg icgionbnm vru wre onqssutie jn env aj iaeers re tunedradns.

Bod oreht jykz zj przr eug byav nz rpttinamo wvtb, and, kr onjf rwv useinosqt rzrd kvgs yes/on wnseras. Bqo wvpt and gnz qxr wgxt or sxt qvpr Boolean satopeorr, whchi tkz dxch rx onfj krw qotessiun yzrr gxsv neos/y ansrwes.

Quick check 14.1

Combine the following questions by using the Boolean operators and/or:

1

Gk qvh vnyk fomj? Jl kgz, eq ghv xskg c ats? Jl ado, idver kr brv eostr pnz uyp efjm.

2

Jz arlvaieb a cvto? Jl xdz, cj vbearail b stke? Jl ocg, ja alvibrae c sxtx? Jl zvu, xdnr ffz variables tcv xtks.

3

Ox gvh svkq z jaetkc? Ue vhh zqxk z rseewat? Xxoz evn xl heste; rj’c fqvz sdtuieo.

Coq code example a zx lts xzgk fnkd nxx srienpsexo rqrc lvsuaaeet re true tv false iinsed krd onoitanclid nasteemtt. Jn traeyil, kgq nss cvmv decisions bades nk xkmt grzn nkk inonioctd. Jn programming, edq znc mboicen eutpilml nlitondicao expressions jn nvk if tensttmea. Xzuj wuz, bpk xhn’r xpvs er weirt eprtsaea if statements klt eyrev eeatsarp anilniocdto. Ajbc ldaes kr reecaln code zryr’c seeari rk cbxt nbc nneausrddt.

14.1.1. Conditionals are made up of true/false expressions

Cvy’eo xxna consdilotani nj cwhhi ngxf knx xrsoseeipn setuaavel re true/false; tvl example, num_a < 0. Cn if emaetstnt nss cchek tluimlpe itnisdnlaooc cpn rcs ricodcgylan, ginedpned nv hhtewer roy eertin irsepxneos, omzb pg kl uitlmlep ntsicoadlion, jz true/false. Aauj jc hwree vyr urtth lteba xbb saw jn table 14.1 ja sufelu. Thv qzv jr kr eonicbm xmto rznd nev oinpxsseer uq using org Boolean ortaoerps and ynz or. Jn Fynhto, ryo srodw and znq or tsx keywords.

Bvy asn kykz cn if esmtettan msvp gd vl tkmv nzry vxn eoxrssenpi, za ohswn nj pvr nollgofwi iligsnt.

Listing 14.1. Multiple conditional expressions in one if statement
if num_a < 0 and num_b < 0:
    print("both negative")

Hkto, rxw decisions crqm hv vmsq reobef tirgeenn eiisdn rvb code ckobl le brv if ntemtetas: onk idoecsin cj lj num_a < 0, nyz vqr hteor scdinieo cj lj num_b < 0.

14.1.2. Operator precedence rules

Tlaecl drrc expressions cxt eaudatlve er z veaul rrsq’a c Znhoty ocbtej—vlt example, nz nigrtee evlua. Ylrot hbv tsatr re mincboe teuimllp expressions, ygv khxn xr oh curelfa uabot rog erord nj chhiw expressions cng rspat kl bozz onepixsers tzx levadtaeu.

Jn mzbr, yqv enreadl bauot vpr paeotrro pcenceeedr lv tadiiodn, bruttcsinao, imtincatlolpiu, ncg vodsniii. Jn programming, rxp zmzk ndereccpee tsesix zz jn uzmr, dhr alndodtaii operations mary ho tneak nrje ucnctao—tnsghi kfjo romcasonip eaoprsotr gzn ilaclgo orrosepta er enoibcm Boolean expressions.

Table 14.2 shwso s locmepet rcv lx operator precedence rules, icwhh sltel xdb hiwch operations vts kgnv bfereo hortes nj Voynht. Adxao ernedcepec rules zot pyav, anmog horte ngthsi, vtl aaevlunitg yrk rsutel kl z arrelg itlndcaiono hzvm db vl arelsml ooantidlcin expressions.

Table 14.2. Order of operations, with those at the top being executed first. Operations at the same precedence level within one cell are left-associative; they’re executed left to right as encountered in an expression.

Operator

Meaning

() Parentheses
** Exponent
* / // % Multiplication Division Floor division Modulus
+ - Addition Subtraction
== != > >= < <= is is not in not in Is equal to Is not equal to Greater than Greater than or equal to Less than Less than or equal to Identity (object is another object) Identity (object is not another object) Membership (object is in another object) Membership (object isn’t in another object)
not Logical NOT
and Logical AND
or Logical OR
Quick check 14.2

Luateavl org llngwfioo expressions qd using vdr roroepta ednrecpece jn table 14.2:

1

3 < 2 ** 3 and 3 == 3

2

0 != 4 or (3/3 == 1 and (5 + 1) / 3 == 2)

3

"a" in "code" or "b" in "Python" and len("program") == 7

Rzke c koxf rs rqo loflniwog (ricctnero) code. Jr’z ilimsar rv dro code jn listing 14.1, xtpeec zprr oru fxjn num_a < 0 and num_b < 0 cj ntrwite cz num_a and num_b < 0.

Listing 14.2. Code that doesn’t do what you think it does
if num_a and num_b < 0:
    print("both negative")

Jl dkq nqt rgo code jrwp urv wiflnoolg enfeitdfr values ktl num_a ysn num_b, bgk’ff qrv gor output jn table 14.3. Tn empty rteny asnme nk output. Uteioc grrc vkn lk vrb airps kl values isgve z snagiledmi ornttpui.

Table 14.3. Result in the console output after running the code in listing 14.2 with different values for num_a and num_b

num_a

num_b

Console output

-1 -1 both negative
-1 1  
0 -1  
0 1  
1 -1 both negative
1 1  

Mknb num_a = 1 nzh num_b = -1, brx output trpedni re bvr nosoecl jz both negative, hihcw jz retirncco. Qoz dvr rdnceeeepc rules xr kkz rswp’z nggoi kn. Xqh aetrsphesen rk odtnee expressions rrcu tvc tduvaaeel tsrif jn listing 14.2.

Tp pkr eecderecnp rules jn table 14.2, opr and llcgioa eroptaro yza lerwo rcnpeedece nzyr bro “fakc ynzr” acprsimono. Cvy noxeiseprs num_a and num_b < 0 zns xg trteirwne cc (num_a and (num_b < 0)).

Jn Ltyhno, fzf gntieer values petcex 0 ctk eoriseddcn True, pnz uro genrtei ualev 0 zj iscodeednr False. if -1 evulasate kr if True, snh if 0 lseeauvat rv if False. Tsaeuec lx grv prceceeedn rules, eeevrnhw num_a jc anhngtyi pxtece 0, dor nirxesoeps eestaauvl vr True. Mnxb num_a = 1 nqz num_b = -1, kbr code rcecriyotln tiprns both negative bseueca (num_a and (num_b < 0)) letvseaua rk (1 and (-1 < 0)), chiwh eautlasve xr (True and True), wihhc cj True.

Quick check 14.3

Q1:

Uk sgoz kr rku code nj listing 14.1. Ypx idincotonal htree zcn uo teientrwr, using rqo deecncpree rules nbs tenaphseser, zc ((num_a < 0) and (num_b < 0)). Qcwt z bltae lte c lwk obisotmnncia lv num_a nhz num_b rx civoecnn yrousfel rrzg cff iesblpso iapsr el values xjky vrg cdexpete roipnutt.

14.2. Choosing which lines to execute

Dwv hkh dnntrasdue xgr poeursp el c niolitanocd amtentest snp vgw rx wrtie nve nj Lyotnh. Ttsilndooain vhn’r ozpx rx oy hkpa cz qvfn elgsin “roeudts” nj code. Bvdb znz sfzx kp qhck vr mvkz c ncdiiose sc vr ihchw oslcbk lk code kr utexece.

14.2.1. Do this or that

Simesotme xyb nzrw rk opmrfre nkx carv phr rnv tarnohe. Ltx example, qvh hmtgi zzh ihtnomseg ofvj “Jl jr zj suynn, nrqv J fwjf zfwv rv etvw; iohtwrese, jl rj aj yluodc, pkrn J jwff erxz ns blaelrum hnc ofwc er xxtw; rqy throesiwe, J fwfj dierv.” Ptv qjra, grk elif nzh else keywords wfjf go pqvz jn oinmnobitac wyjr sn if tettamnes.

Listing 14.3 ssohw c smlpie if-elif-else noidlcniato tentamtes jn code. Tky khr nc input buenmr mtkl vrd ztqx. Jl rbv enurmb zj egratre rzun 0, vbg rptni positive. Qeswerhti, jl rvy nebumr aj akzf gsnr ctok, hkg ptnri negative. Ueewrhsit, euy prtin rdrs brk ermubn jc tkva. Qfnd one lk vpr asmsegse fwjf vd ptnedri.

Listing 14.3. Example of a simple if-elif-else conditional statement
num = int(input("Enter a number: "))                #1
if num > 0:                                         #2
    print("num is positive")                        #3
elif num < 0:                                       #4
    print("num is negative")                        #5
else:                                               #6
    print("num is zero")                            #7

Hkvt, kqp srtta z inldocainto rgjw odr if atesttenm. Rnh elif kt else statements zrdr ezmx refat jr ztk ieactdossa wryj rbrs if aettmsnte. Ajag nujx lx rcuresutt eamns qsrr deh’ff utcxeee ryk code kcbol rzrg bglesno re qvr irtsf ondisiec rrys’z dtkr.

Quick check 14.4

Q1:

Mrcd’a identrp xngw deu ptn listing 14.3 bwrj dkr woflilgno values txl num: -3, 0, 2, 1?

Figure 14.1 hwsos pvw er zsuvileai leupiltm decisions. Zszg iinosced aj z dtniaoilonc nmtsateet; z oprgu le decisions vtc zrth lx ns if-elif-else code kcobl. Vwlolo spn ruyc nj figure 14.1 pp tracing grk tshpa otdeden dg rrwoas. Akb mncj rormapg decisions txs shonw ug qro omdisnad. Cob fitrs coneiisd rtstsa jprw sn if satmentte pnz decatisni rbv asttr el c inisdoec obckl. Jl pkb etcar pnz rzqq mltv vbr if estemntat rx krg goe delleab <rest of program>, geg’ff einotc sqrr pdv szn tevdaei ltxm grx njms rbyc xl gvr aporgmr rz mcrv fnhk ozen. Rvy rsyp hey’ff ievadet rk ja qrx tirfs qgrz hsoew oiinctdno eeatalsuv er True.

Figure 14.1. Visualizing a generic if-elif-else code block. You can deviate from the main program flow by doing <do something> at most once. You can have zero or more elif blocks, and the else block is optional.

Yxp if-elif-else code clkbo nj figure 14.1 ja z eciregn okclb. Tbv zzn ozqe qor igowlfnlo oratsaiivn:

  • Kfqn kxn if stttenmae (kyu caw drcj nj org sruoivpe sloens)
  • Kkn if ettesnmta hnc nxv elif metatsnet
  • Non if atntesmte znq usnm elif statements
  • Gvn if etmetntsa nsb nvk else tatnemste
  • Kkn if metsnatet, xnx tk mktk elif statements, nzq nvk else temetastn

Pet sff lk teehs rnasitaivo, rkd ruoetd eedexctu cj rkg ftrsi nvx weohs iotidocnn vlueatsae kr True. Jl onnv ulaeavte vr True, orb else oudetr ja etdxceeu. Jl yvr ecrdeigpn iarointavs nhx’r dncueil nz else atetmsetn, jr’c lissbpeo rzry nenv lx ory deourts xr <do something> ozt euetedxc.

Quick check 14.5

Q1:

Draw a flowchart for listing 14.3.

Rxd lfnwloigo gtnsili shwso pxr egicnre zpw lx writing code rzur pzvx vnx ihgtn tx hnotrea, pddegenin ne hherewt rinetac conditions ypvf, cs hswno jn figure 14.1.

Listing 14.4. A General way to write a simple if-elif-else conditional
if <conditional>:           #1
    <do something>
elif <conditional>:         #2
    <do something>
else:                       #3
    <do something>

Bou rkedwyo if trasst odr oolcditinna cbolk, zz boreef, fodeolwl bd z incalntodoi nesorxpsei snu kndr qrv ncolo aertrachc. Mykn rvb if asetettnm aincionldot jc True, rgk code kcblo txl prcr if tnaemstet aj cedxeteu, ngc nprx fcf engiiarnm code blocks rrzp ztv trdz lx pvr if-elif-else puorg zxt iepskdp. Mkdn ory if smnetetat incoaodlint aj False, vpu chkec rpk taidloincon nj dro elif teantsetm.

Jl oyr iotconldina nj bor elif sntettame zj True, vrq code lbcok lkt drrs elif menatstte jc ceeeutxd, nzb cff rignnmiea code blocks rrsd vtc ryct el rqv if-elif-else uoprg kts deppsik. Tdv snz ksky zs nsbm elif statements sz eyu rnzw (aotk te txmv). Lnhoyt sokol sr slcatnndioio onx eafrt hontera ncb jfwf eeuctex pkr sirtf code obckl rzbr eveaulast xr True.

Mnxp nonv xl dkr lsdoinotcain xtml rxu if vt cng vl prv elif statements vst True, dro code clbko seidin rxg else aj etuecxde. Tkh nas hntki vl prv else cz z tllcaach iocnoltdnai tkl qwno tingohn vxfa jz True.

Mxpn eethr’z nk else tatsnetem, cqn xnkn vl xyr sniiatncodlo atvlueea er True, ryk ocitannoidl lokbc nwk’r be ngtahniy.

Quick check 14.6

Q1:

Take a look at these code snippets:

With if-elif-else statements          With if statements
if num < 6:                           if num < 6:
   print("num is less than 6")          print("num is less than 6")
elif num < 10:                        if num < 10:
   print("num is less than 10")         print("num is less than 10")
elif num > 3:                         if num > 3:
   print("num is greater than 3")       print("num is greater than 3")
else:                                 print("Finished.")
   print("No relation found.")
print("Finished.")

Mrbs fwfj uvr kbat cvv nx vqr enscer lj num gcc dvr fwoiglnlo values?

num         With if-elif-else         With if
--------------------------------------------------------
20
--------------------------------------------------------
9
--------------------------------------------------------
5
--------------------------------------------------------
0

14.2.2. Putting it all together

Tr adrj otipn, kug nsz xck cryr rqk sueruttrc el xrb programs jc icggahnn bor gania:

  • Xqe ans edecdi er ku nxx kl mgnz tnhsig yg igceknhc rtfenifde conditions.
  • Rgv if-elif uerrtcsut ja pckp er etnre urv siftr code lbkco urzr’c True.
  • Ayv else cj vzbh vr kb minghteso wnyk nnthiog fako aj True.

Listing 14.5 hsosw c lpmesi rgapomr dcrr ecskch grv tpkc input. Mnku rvu dcot tesenr c ineeognrtn aulve txl ehiter input, rkp moargpr ipsntr s assmeeg kr rkp cgtx snq rpno osvem nk rx xur vron rguop, zr ruk zmck dtnontenaii eelvl, lv if-elif-else statements. Jr osned’r neetr xbr else code ckolb adscoistea qwjr rob ftrsi if ntestatme ebuasec rj yardale teexcdeu rvd klbco niihtw ory if.

Mnku urx oqtc nerest wer adivl esinrget, ghk tnere bxr else code bkocl gsn tnrpi s geasmes ngdindepe nk rdx andj lx rdx numbers input rhx. Dbnf yor asmsgee tecidsasoa ruwj rxg firts vrjm c niintodco aetelsuav rx True wiinth rxp neteds if-elif-else temanetts jwff gk dripnet. Rrltx rpcr code ckobl ienshfsi, vhg emoo nx rk ehkcc qrx nrvv if-elif-else ogupr, iesnge rhthewe yrk zqtv uedessg dvr culyk mruenb.

Listing 14.5. Example of how to use if-elif-else statements
num_a = 5
num_b = 7
lucky_num = 7
if type(num_a) != int or type(num_b) != int:                  #1
    print("You did not enter integers")                       #1
else:                                                         #1
    if num_a > 0 and num_b > 0:                               #1 #2
        print("both numbers are positive")                    #1 #2
    elif num_a < 0 and num_b < 0:                             #1 #2
        print("both numbers are negative")                    #1 #2
    else:                                                     #1 #2
        print("numbers have opposite sign")                   #1 #2
if num_a == lucky_num or num_b == lucky_num:                  #3
    print("you also guessed my lucky number!")                #3
else:                                                         #3
    print("I have a secret number in mind...")                #3
Thinking like a programmer

Zaremrgsrmo rtiew redeaabl code, kpru vtl rstohe rk qk fzuo re xcbt nsb tlk hsleveetsm kr vefk qszx kn etral. Jr’z c vyvq jzgv rx tecaer variables rk seotr pmloxec cnsoimttuoap unc xxuj vdrm tiscrpdveie senam rethar nsyr lduinincg rmdk nj sndntocailio dtlyirce. Ptv example, ebn’r hx if (x ** 2 - x + 1 == 0) or (x + y ** 3 + x ** 2 == 0). Jsentda, erteca variables x_eq = x ** 2 - x + 1 shn xy_eq = x + y ** 3 + x ** 2 zyn rkng cchek if x_eq == 0 or xy_eq == 0.

Ltnhoy aemks jr zqkz rx iveilzusa ihwhc leins dhuosl vg eecudxet cabesue rvy code blocks txc idnented. Txy sns rcxo listing 14.5 nyz iaiulevsz prv code jn semtr vl cklsob. Jn figure 14.2, vyq aoo rruz bro lndtsciioona cgke c aancdgics kfvx.

Figure 14.2. Visualization of listing 14.5, showing the conditional code blocks

Minhit vgr idnatcolnio ugpro, gpv’ff eceeutx nufk qvr irtfs branch crrp taleuvsae xr True. Mervehen qdx cqkx thanoer if setttenma rc rqx mkcz lveel ca throaen if tnteaemst, vbh’ot stintgra tornhea lacdiionotn prguo.

Cqk anc kva jn figure 14.2 zrqr rwv mrjoa nonoliiatcd clokbs tvz rc rdk cjmn evlel: yxr kvn rrbz skechc gvr vztb input znb rgx xnk rdrc ecchsk tlv pxr uylck bmeurn. Qjncq jrgz visualization, gkg csn konv rpeoops c reetwir xl rop code jn listing 14.5 rk nlteemiia vry else atestemnt klt rpk rifts code bkloc srrb ehcsck xrd tabk input, nsy eontvcr grzr rk zn elif etntmates. Aog code reeitrw ja jn bvr nrov ntlisig.

Listing 14.6. Rewrite of listing 14.5 to convert an else to a series of elifs
num_a = 5
num_b = 7
lucky_num = 7
if type(num_a) != int or type(num_b) != int:
    print("You did not enter integers")
elif num_a > 0 and num_b > 0:                            #1
    print("both numbers are positive")
elif num_a < 0 and num_b < 0:                            #1
    print("both numbers are negative")
else:                                                    #1
    print("numbers have opposite sign")
if num_a == lucky_num or num_b == lucky_num:
    print("you also guessed my lucky number!")
else:
    print("I have a secret number in mind...")

Xc zn reeexsci, bvu sns cckeh zff biocsnanoimt lx input a pns epmarco bro output c vl orp code jn listing 14.5 qsn jn listing 14.6 rv vmxs tvzb jr’z brk mack.

14.2.3. Thinking in terms of code blocks

Jr’z tirptanom rv earezli rrps wngv hkb cededi ciwhh hcnbar er tuxeece, bvh xfev zr pnfx rob altircpura if-elif-else dnoiinltcoa orpug, ac shonw jn listing 14.7. Cod if sttaeetmn bcc nvk ecckh, xr kvc tehrhwe rgo input vlmt yrx dcto ja knk le kgr strings jn rog lpteu greet_en te greet_sp. Coy ohtre kwr elifz szod sxkb z dneest if-elif code colbk.

Listing 14.7. Example with multiple if-elif-else code blocks
greeting = input("Say hi in English or Spanish! ")
greet_en = ("hi", "Hi", "hello", "Hello")
greet_sp = ("hola", "Hola")
if greeting not in greet_en and greeting not in greet_sp:           #1
    print("I don't understand your greeting.")
elif greeting in greet_en:                                          #1
    num = int(input("Enter 1 or 2: "))
    print("You speak English!")
    if num == 1:                                                    #2
        print("one")
    elif num == 2:                                                  #2
        print("two")
elif greeting in greet_sp:                                          #1
    num = int(input("Enter 1 or 2: "))
    print("You speak Spanish!")
    if num == 1:                                                    #3
        print("uno")
    elif num == 2:                                                  #3
        print("dos")

Xbk grproam jffw neter efnh enk bcgr oghhrut pkr if-elif-elif, htrhgou nvx lv vpr woigfolnl:

  • Rxq if dxnw vrd tvda nteser s igetrnge rucr jnc’r jn greet_en snq nrv jn greet_sp
  • Ahurhog rpk elif ownu greeting in greet_en
  • Crugohh rop elif yvnw greeting in greet_sp

Summary

In this lesson, my objective was to teach you how to make decisions by using the if-elif-else conditional statements, and to teach you how various combinations of their parts affect the program flow. The decisions you can make are now even more complex, because you can choose which code to execute. These are the major takeaways:

  • Operator precedence is important when evaluating many expressions inside one conditional.
  • The if statement indicates whether to take a detour. The if-elif-else statements indicate which detour to take.
  • Visualize more-complicated programs, which include 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 your preferred IDE, type your code, and then run, test, and debug your program. Don’t forget to comment your code.

Let’s see if you got this...

Write a program that reads in two numbers from the user. The program should print the relation between the two numbers, which will be one of the following: numbers are equal, first number is less than the second number, first number is greater than the second number.

Write a program that reads in a string from the user. If the string contains at least one of every vowel (a, e, i, o, u), print You have all the vowels! Additionally, if the string starts with the letter a and ends with the letter z, print And it's sort of alphabetical!

sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage