Python Programming: An Introduction to Computer Science

(Nora) #1
5.4.GRAPHINGFUTUREVALUE 71

0.0K

2.5K

5.0K

7.5K

10.0K

(40,230)

320

(0,0)

(319,239)
25

10
40

50
(315,230)

240

Figure5.8:Positionofelementsinfuturevaluebargraph.

Calculate xll = 25 * year+ 40
Calculate height= principal * 0.02
Draw a rectanglefrom (xll, 230) to (xll+25, 230 - height)

Thevariablexllstandsforxlowerleft—thexvalueofthelowerleftcornerofthebar.
Puttingallofthistogetherproducesthedetailedalgorithmshownbelow.


Print an introduction
Get value of principaland apr from user
Create a 320x240 GraphWintitled ‘‘Investment Growth Chart’’
Draw label " 0.0K"at (20,230)
Draw label " 2.5K"at (20, 180)
Draw label " 5.0K"at (20, 130)
Draw label " 7.5K"at (20, 80)
Draw label "10.0K"at (20, 30)
Draw a rectangle from(40, 230) to (65, 230 - principal 0.02)
for year running froma value of 1 up through 10:
Calculate principal= principal
(1 + apr)
Calculate xll = 25 year+ 40
Draw a rectanglefrom (xll, 230) to (xll+25, 230 - principal
0.02)
Wait for user to pressEnter


Whew!Thatwasa lotofwork,butwearefinallyreadytotranslatethisalgorithmintoactualPython
code.Thetranslationis straightforwardusingobjectsfromthegraphicsmodule.Here’s theprogram:


futval_graph.py


from graphics import*


def main():


Introduction


print "This programplots the growth of a 10-year investment."


# Get principaland interest rate
principal = input("Enterthe initial principal: ")
apr = input("Enterthe annualized interest rate: ")
Free download pdf