Python Programming: An Introduction to Computer Science

(Nora) #1
86 CHAPTER6.DEFININGFUNCTIONS

# 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)

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

Thisis certainlya workableprogram,butthereis a naggingissueofprogramstylethatreallyshouldbe
addressed.Noticethatthisprogramdrawsbarsintwo differentplaces.Theinitialbaris drawnjustbefore
theloop,andthesubsequentbarsaredrawninsideoftheloop.
Havingsimilarcodelike thisintwo placeshassomedrawbacks.Obviously, oneissueis havingtowrite
thecodetwice.A moresubtleproblemis thatthecodehasto bemaintainedin two differentplaces.Shouldwe
decidetochangethecolororotherfacetsofthebars,wewouldhave tomake surethesechangesoccurredin
bothplaces.Failingtokeeprelatedpartsofthecodein synchis a commonprobleminprogrammaintenance.
Functionscanbeusedtoreducecodeduplicationandmake programsmoreunderstandableandeasierto
maintain.Beforefixingupthefuturevalueprogram,let’s take lookat whatfunctionshave tooffer.


6.2 Functions,Informally.


Youcanthinkofa functionasasubprogram—asmallprogram insideofa program.Thebasicideaofa
functionis thatwewritea sequenceofstatementsandgive thatsequencea name.Theinstructionscanthen
beexecutedat any pointintheprogrambyreferringtothefunctionname.
Thepartoftheprogramthatcreatesa functioniscalledafunctiondefinition. Whena functionis
subsequentlyusedina program,wesaythatthedefinitioniscalledorinvoked. A singlefunctiondefinition
maybecalledat many differentpointsofa program.
Let’s take a concreteexample. Supposeyouwanttowritea programthatprintsoutthelyricstothe
“Happy Birthday”song.Thestandardlyricslooklike this.


Happy birthday to you!
Happy birthday to you!
Happy birthday, dear.
Happy birthday to you!


We’regoingtoplaywiththisexampleintheinteractive Pythonenvironment.Youmightwanttofireup
Pythonandtrysomeofthisoutforyourself.
Asimpleapproachtothisproblemis tousefourprintstatements.Here’s aninteractive sessionthat
createsa programforsingingHappy BirthdaytoFred.





def main():
print "Happybirthday to you!"
print "Happybirthday to you!"
print "Happybirthday, dear Fred."
print "Happybirthday to you!"





We canthenrunthisprogramtogetourlyrics.





main()
Happy birthday to you!
Happy birthday to you!
Happy birthday, dearFred.
Happy birthday to you!




Free download pdf