Python Programming: An Introduction to Computer Science

(Nora) #1
74 CHAPTER5. OBJECTSANDGRAPHICS

win = GraphWin("Investment Growth Chart", 320, 240)
win.setCoords(0.0,0.0, 10.0, 10000.0)


Thencreatinga barforany valuesofyearandprincipalwouldbesimple.Eachbarstartsat thegiven
yearanda baselineof0 andgrowstothenextyearanda heightequaltoprincipal.


bar = Rectangle(Point(year, 0), Point(year+1, principal))


Thereis a smallproblemwiththisscheme.CanyouseewhatI have forgotten?Thebarswillfilltheentire
window;wehaven’t leftany roomforlabelsormarginsaroundtheedges.Thisis easilyfixedbyexpanding
thecoordinatesofthewindow slightly. Sinceourbarsstartat0,wecanlocatetheleftsidelabelsat -1.We
canadda bitofwhitespacearoundthegraphbyexpandingthecoordinatesslightlybeyondthatrequiredfor
ourgraph.A littleexperimentationleadstothiswindow definition:


win = GraphWin("Investment Growth Chart", 320, 240)
win.setCoords(-1.75,-200, 11.5, 10400)


Hereis theprogramagain,usingthealternative coordinatesystem:

futval_graph2.py


from graphics import*


def main():


Introduction


print "This programplots the growth of"
print "a 10-yearinvestment."


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

# Create a graphicswindow with labels on left edge
win = GraphWin("Investment Growth Chart", 320, 240)
win.setBackground("white")
win.setCoords(-1.75,-200, 11.5, 10400)
Text(Point(-1,0), ’ 0.0K’).draw(win)
Text(Point(-1,2500), ’ 2.5K’).draw(win)
Text(Point(-1,5000), ’ 5.0K’).draw(win)
Text(Point(-1,7500), ’ 7.5k’).draw(win)
Text(Point(-1,10000), ’10.0K’).draw(win)

# Draw bar for initialprincipal
bar = Rectangle(Point(0, 0), Point(1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)

# Draw a bar for eachsubsequent year
for year in range(1,11):
principal = principal* (1 + apr)
bar = Rectangle(Point(year, 0), Point(year+1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
Free download pdf