24 CHAPTER2. WRITINGSIMPLEPROGRAMS
by: John M. Zelle
def main():
print "This programcalculates the future value of a 10-yearinvestment."
principal = input("Enterthe initial principal: ")
apr = input("Enterthe annualized interest rate: ")
for i in range(10):
principal = principal* (1 + apr)
print "The amountin 10 years is:", principal
main()
NoticethatI have addeda fewblanklinestoseparatetheInput,Processing,andOutputportionsofthe
program.Strategicallyplaced“whitespace”canhelpmake yourprogramsmorereadable.
That’s aboutit forthisexample;I leave thetestinganddebuggingasanexerciseforyou.
2.8 Exercises
- Listanddescribeinyourownwordsthesixstepsinthesoftwaredevelopmentprocess.
- Writeoutthechaos.pyprogram(Section1.6)andidentifythepartsoftheprogramasfollows:
Circleeachidentifier.
Underlineeachexpression.
Puta commentattheendofeachlineindicatingthetypeofstatementonthatline(output,as-
signment,input,loop,etc.) - A user-friendlyprogramshouldprintanintroductionthattellstheuserwhattheprogramdoes.Modify
theconvert.pyprogram(Section2.2)toprintanintroduction. - Modifytheavg2.pyprogram(Section2.5.3)tofindtheaverageofthreeexamscores.
- Modifythefutval.pyprogram(Section2.7)sothatthenumberofyearsfortheinvestmentis also
a userinput.Make suretochangethefinalmessagetoreflectthecorrectnumberofyears. - Modifytheconvert.pyprogram(Section2.2)witha loopsothatit executes5 timesbeforequitting
(i.e.,it converts5 temperaturesina row). - Modifytheconvert.pyprogram(Section2.2)sothatit computesandprintsa tableofCelsius
temperaturesandtheFahrenheitequivalentsevery 10 degreesfrom0Cto100C. - Writea programthatconvertsfromFahrenheittoCelsius.
- Modifythefutval.pyprogram(Section2.7)sothatit computestheactualpurchasingpowerof
theinvestment,takinginflationintoaccount.Theyearlyrateofinflationwillbea secondinput.The
adjustmentis givenbythisformula:
principal = principal/(1+ inflation)