Future Value with a Function

Now that you've seen how defining functions can help solve the code duplication problem, let's return to the future value graph. Recall the problem is that bars of the graph are printed at two different places in the program.

The code just before the loop looks like this.

# Draw bar for initial principal bar = Rectangle(Point(0, 0), Point(1, principal))

bar.setFill("green")

bar.setWidth(2)

bar.draw(win)

And the code inside of the loop is as follows.

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

bar.setFill("green")

bar.setWidth(2)

bar.draw(win)

Let's try to combine these two into a single function that draws a bar on the screen.

In order to draw the bar, we need some information. Specifically, we need to know what year the bar will be for, how tall the bar will be, and what window the bar will be drawn in. These three values will be supplied as parameters for the function. Here's the function definition.

def drawBar(window, year, height):

# Draw a bar in window for given year with given height bar = Rectangle(Point(year, 0), Point(year+1, height)) bar.setFill("green")

bar.setWidth(2) bar.draw(window)

To use this function, we just need to supply values for the three parameters. For example, if win is a GraphWin, we can draw a bar for year 0 and a principal of $2,000 by invoking drawBar like this.

drawBar(win, 0, 2000)

Incorporating the drawBar function, here is the latest version of our future value program.

# futval_graph3.py from graphics import *

def drawBar(window, year, height):

# Draw a bar in window starting at year with given height bar = Rectangle(Point(year, 0), Point(year+1, height)) bar.setFill("green")

bar.setWidth(2) bar.draw(window)

# Introduction print "This program plots the growth of a 10-year investment."

# Get principal and interest rate principal = input("Enter the initial principal: ") apr = input("Enter the annualized interest rate: ")

# Create a graphics window 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 initial principal drawBar(win, 0, principal)

# Draw a bar for each subsequent year for year in range(1, 11):

principal = principal * (1 + apr) drawBar(win, year, principal)

raw_input("Press <Enter> to quit.")

You can see how drawBar has eliminated the duplicated code. Should we wish to change the appearance ofthe bars in the graph, we only need to change the code in one spot, the definition ofdrawBar. Don'tworry yet if you don't understand every detail of this example. You still have some things to learn about functions.

0 0

Post a comment