Python Programming: An Introduction to Computer Science

(Nora) #1
6.4.FUNCTIONSANDPARAMETERS:THEGORY DETAILS 91

WhenPythoncomestoa functioncall,it initiatesa four-stepprocess.



  1. Thecallingprogramsuspendsat thepointofthecall.

  2. Theformalparametersofthefunctiongetassignedthevaluessuppliedbytheactualparametersinthe
    call.

  3. Thebodyofthefunctionis executed.

  4. 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

Free download pdf