Python Programming: An Introduction to Computer Science

(Nora) #1
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



  1. Listanddescribeinyourownwordsthesixstepsinthesoftwaredevelopmentprocess.

  2. Writeoutthechaos.pyprogram(Section1.6)andidentifythepartsoftheprogramasfollows:
    Circleeachidentifier.
    Underlineeachexpression.
    Puta commentattheendofeachlineindicatingthetypeofstatementonthatline(output,as-
    signment,input,loop,etc.)

  3. A user-friendlyprogramshouldprintanintroductionthattellstheuserwhattheprogramdoes.Modify
    theconvert.pyprogram(Section2.2)toprintanintroduction.

  4. Modifytheavg2.pyprogram(Section2.5.3)tofindtheaverageofthreeexamscores.

  5. Modifythefutval.pyprogram(Section2.7)sothatthenumberofyearsfortheinvestmentis also
    a userinput.Make suretochangethefinalmessagetoreflectthecorrectnumberofyears.

  6. Modifytheconvert.pyprogram(Section2.2)witha loopsothatit executes5 timesbeforequitting
    (i.e.,it converts5 temperaturesina row).

  7. Modifytheconvert.pyprogram(Section2.2)sothatit computesandprintsa tableofCelsius
    temperaturesandtheFahrenheitequivalentsevery 10 degreesfrom0Cto100C.

  8. Writea programthatconvertsfromFahrenheittoCelsius.

  9. Modifythefutval.pyprogram(Section2.7)sothatit computestheactualpurchasingpowerof
    theinvestment,takinginflationintoaccount.Theyearlyrateofinflationwillbea secondinput.The
    adjustmentis givenbythisformula:


principal = principal/(1+ inflation)
Free download pdf