6.3.FUTUREVALUEWITHA FUNCTION 89
sing("Lucy")
print
sing("Elmer")
6.3 FutureValuewitha Function.
Nowthatyou’ve seenhowdefiningfunctionscanhelpsolve thecodeduplicationproblem,let’s returnto
thefuturevaluegraph.Recalltheproblemis thatbarsofthegraphareprintedat two differentplacesinthe
program.
Thecodejustbeforethelooplookslike this.
Draw bar for initialprincipal
bar = Rectangle(Point(0, 0), Point(1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
Andthecodeinsideoftheloopis asfollows.
bar = Rectangle(Point(year, 0), Point(year+1, principal))
bar.setFill("green")
bar.setWidth(2)
bar.draw(win)
Let’s trytocombinethesetwo intoa singlefunctionthatdrawsa baronthescreen.
Inordertodraw thebar, weneedsomeinformation.Specifically, weneedtoknow whatyearthebarwill
befor, how tallthebarwillbe,andwhatwindow thebarwillbedrawnin.Thesethreevalueswillbesupplied
asparametersforthefunction.Here’s thefunctiondefinition.
def drawBar(window,year, height):
Draw a bar in windowfor given year with given height
bar = Rectangle(Point(year, 0), Point(year+1, height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(window)
To usethisfunction,wejustneedtosupplyvaluesforthethreeparameters. Forexample,ifwinisa
GraphWin, wecandraw a barforyear0 anda principalof$2,000byinvokingdrawBarlike this.
drawBar(win, 0, 2000)
IncorporatingthedrawBarfunction,hereis thelatestversionofourfuturevalueprogram.
futval_graph3.py
from graphics import*
def drawBar(window,year, height):
Draw a bar in windowstarting at year with given height
bar = Rectangle(Point(year, 0), Point(year+1, height))
bar.setFill("green")
bar.setWidth(2)
bar.draw(window)
def main():
Introduction
print "This programplots the growth of a 10-year investment."