Python Programming: An Introduction to Computer Science

(Nora) #1

Chapter 6


Defining Functions


Theprogramsthatwehave writtensofar comprisea singlefunction,usuallycalledmain. We have alsobeen
usingpre-writtenfunctionsandmethodsincludingbuilt-inPythonfunctions(e.g.,abs), functionsfromthe
Pythonstandardlibraries(e.g.,math.sqrt,string.split), andobjectmethodsfromthegraphics
module(e.g.,myPoint.getX()).
Functionsareanimportanttoolforbuildingsophisticatedprograms.Thischaptercoversthewhysand
howsofdesigningyourownfunctionstomake yourprogramseasiertowriteandunderstand.


6.1 TheFunctionofFunctions


Inthepreviouschapter, welookedat a graphicsolutiontothefuturevalueproblem.Thisprogrammakesuse
ofthegraphicslibrarytodraw a barchartshowingthegrowthofaninvestment.Hereis theprogramas
weleftit:


futval_graph2.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: ")

# Create a graphicswindow with labels on left edge
win = GraphWin("Investment Growth Chart", 640, 480)
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)

85
Free download pdf