Python Programming: An Introduction to Computer Science

(Nora) #1
22 CHAPTER2. WRITINGSIMPLEPROGRAMS

Theinterestingandusefulthingaboutloopsis thewaythatthey alterthe“flow ofcontrol”ina program.
Usuallywethinkofcomputersasexecutinga seriesofinstructionsinstrictsequence.Introducinga loop
causesPythontogobackanddosomestatementsoverandoveragain. Statementslike theforloopare
calledcontrolstructuresbecausethey controltheexecutionofotherpartsoftheprogram.
Someprogrammersfindit helpfultothinkofcontrolstructuresintermsofpicturescalledflowcharts. A
flowchartis a diagramthatusesboxestorepresentdifferentpartsofa programandarrowsbetweentheboxes
toshowthesequenceofeventswhentheprogramis running.Figure2.1depictsthesemanticsofthefor
loopasa flowchart.


yes

more items in <sequence>
no

<var> = next item

<body>

Figure2.1:Flowchartofaforloop.

If youarehavingtroubleunderstandingtheforloop,youmightfindit usefultostudytheflowchart.
Thediamondshapeboxintheflowchartrepresentsa decisionintheprogram.WhenPythongetsthetheloop
heading,it checkstoseeif thereareany (more)itemsleftif thesequence.If theansweris yes,thevalueof
theloopindex variableis settothenextiteminthesequence,andthentheloopbodyis executed.Oncethe
bodyis complete,theprogramgoesbacktotheloopheadingandchecksforanothervalueinthesequence.
Theloopquitswhentherearenomoreitems,andtheprogrammovesontothestatementsthatcomeafterthe
loop.


2.7 ExampleProgram:FutureValue


Let’s closethechapterwithonemoreexampleoftheprogrammingprocessinaction.We wanttodevelopa
programtodeterminethefuturevalueofaninvestment.Let’s startwithananalysisoftheproblem(require-
ments).Youknow thatmoney thatis depositedina bankaccountearnsinterest,andthisinterestaccumulates
astheyearspass.Howmuchwillanaccountbeworthtenyearsfromnow?Obviouslyit dependsonhow
muchmoney westartwith(theprincipal)andhow muchinteresttheaccountearns.Giventheprincipaland
theinterestrate,a programshouldbeabletocalculatethevalueoftheinvestmenttenyearsintothefuture.
We continuebydevelopingtheexactspecificationsfortheprogram.Recall,thisis a descriptionofwhat
theprogramwilldo.Whatexactlyshouldtheinputsbe?We needtheuserto entertheinitialamountto invest,
theprincipal.We willalsoneedsomeindicationofhow muchinteresttheaccountearns.Thisdependsboth
ontheinterestrateandhow oftentheinterestis compounded.Onesimplewayofhandlingthisis tohave the
userenteranannualizedpercentagerate.Whatevertheactualinterestrateandcompoundingfrequency, the
annualizedratetellsushow muchtheinvestmentaccruesinoneyear. If theannualizedinterestis 3%,thena

Free download pdf