6.4.FUNCTIONSANDPARAMETERS:THEGORY DETAILS 91
WhenPythoncomestoa functioncall,it initiatesa four-stepprocess.
- Thecallingprogramsuspendsat thepointofthecall.
- Theformalparametersofthefunctiongetassignedthevaluessuppliedbytheactualparametersinthe
call. - Thebodyofthefunctionis executed.
- Controlreturnstothepointjustafterwherethefunctionwascalled.
ReturningtotheHappy Birthdayexample,let’s tracethroughthesingingoftwo verses.Hereis partof
thebodyfrommain.
sing("Fred")
print
sing("Lucy")
...
WhenPythongetstosing("Fred"), executionofmainis temporarilysuspended.Atthispoint,Python
looksupthedefinitionofsingandseesthatit hasa singleformalparameter,person. Theformalparameter
is assignedthevalueoftheactual,soit is asif wehadexecutedthisstatement:
person = "Fred"
A snapshotofthissituationis shownin Figure6.1.Noticethevariablepersoninsideofsinghasjustbeen
initialized.
sing("Fred")
print
sing("Lucy")
def main(): def sing(person): happy()
happy()
print "Happy birthday, dear", person + "."
happy()
person = "Fred"
person: "Fred"
Figure6.1:Illustrationofcontroltransferringtosing.
Atthispoint,Pythonbeginsexecutingthebodyofsing. Thefirststatementis anotherfunctioncall,this
onetohappy. Pythonsuspendsexecutionofsingandtransferscontroltothecalledfunction.Thebodyof
happyconsistsofa singleprint. Thisstatementis executed,andthencontrolreturnstowhereit leftoff
insing. Figure6.2showsa snapshotoftheexecutionsofar.
sing("Fred")
print
sing("Lucy")
def main(): def sing(person): happy()
happy()
print "Happy birthday, dear", person + "."
happy()
def happy():
person = "Fred" print "Happy Birthday to you!"
person: "Fred"
Figure6.2:Snaphotofcompletedcalltohappy.
ExecutioncontinuesinthismannerwithPythonmakingtwo moresidetripsbacktohappytocomplete
theexecutionofsing. WhenPythongettotheendofsing, controlthenreturnstomainandcontinues
immediatelyafterthefunctioncall.Figure6.3showswhereweareatthatpoint.Noticethattheperson