92 CHAPTER6.DEFININGFUNCTIONS
sing("Fred")
print
sing("Lucy")
def main(): def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Fred"
Figure6.3:Snaphotofcompletedcalltosing.
variableinsinghasdisappeared.Thememoryoccupiedbylocalfunctionvariablesis reclaimedwhenthe
functionfinishes.Localvariablesdonotretainany valuesfromonefunctionexecutiontothenext.
Thenextstatementtoexecuteis thebareprintstatementinmain. Thisproducesa blanklineinthe
output.ThenPythonencountersanothercalltosing. Asbefore,controltransferstothefunctiondefinition.
Thistimetheformalparameteris"Lucy". Figure6.4showsthesituationassingbeginstoexecuteforthe
secondtime.
sing("Fred")
print
sing("Lucy")
def main(): def sing(person): happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Lucy"
person: "Lucy"
Figure6.4:Snaphotofsecondcalltosing.
Now we’ll fastforwardtotheend.Thefunctionbodyofsingis executedforLucy (withthreesidetrips
throughhappy) andcontrolreturnstomainjustafterthepointofthefunctioncall.Now wehave reached
thebottomofourcodefragment,asillustratedbyFigure6.5.Thesethreestatementsinmainhave caused
singtoexecutetwiceandhappytoexecutesixtimes.Overall,ninetotallinesofoutputweregenerated.
sing("Fred")
print
sing("Lucy")
def main(): def sing(person):
happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Lucy"
Figure6.5:Completionofsecondcalltosing.
Hopefullyyou’regettingthehangofhow functioncallsactuallywork.Onepointthatthisexampledid
notaddressis theuseofmultipleparameters. Whena functiondefinitionhasseveralparameters,theactual
parametersarematchedupwiththeformalparametersbyposition. Thefirstactualparameteris assignedto
thefirstformalparamter, thesecondactualis assignedtothesecondformal,etc.
Asanexample,lookagainattheuseofthedrawBarfunctionfromthefuturevalueprogram.Hereis
thecalltodraw theinitialbar.
drawBar(win, 0, principal)
WhenPythontransferscontroltodrawBar, theseparametersarematcheduptotheformalparametersin
thefunctionheading.
def drawBar(window,year, height):