chapter five: functions · 2016-09-26 · ch05.pptx author: donald patterson created date:...
TRANSCRIPT
Chapter Five: Functions
Chapter Goals • Tobeabletoimplementfunc0ons• Tobecomefamiliarwiththeconceptofparameterpassing• Todevelopstrategiesfordecomposingcomplextasksintosimplerones• Tobeabletodeterminethescopeofavariable• Tolearnhowtothinkrecursively
Inthischapter,youwilllearnhowtodesignandimplementyourownfunc7ons
Usingtheprocessofstepwiserefinement,youwillbeabletobreakupcomplextasksintosetsofcoopera7ngfunc7ons
9/23/16 Page 2
Contents • Func0onsasBlackBoxes• Implemen0ngandTes0ngFunc0ons• ParameterPassing• ReturnValues• Func0onswithoutReturnValues• ReusableFunc0ons• StepwiseRefinement• VariableScope• Graphics:BuildinganImageProcessingToolkit• RecursiveFunc0ons
9/23/16 Page 3
Functions as Black Boxes SECTION 5.1
9/23/16 Page 4
Functions as Black Boxes • Afunc0onisasequenceofinstruc0onswithaname
• Forexample,theroundfunc0on,whichwasintroducedinChapter2,containsinstruc0onstoroundafloa0ng-pointvaluetoaspecifiednumberofdecimalplaces
9/23/16 Page 5
Calling Functions • Youcallafunc0oninordertoexecuteitsinstruc0onsprice=round(6.8275,2)#Setsresultto6.83
• Byusingtheexpressionround(6.8275,2),yourprogramcallstheroundfunc0on,askingittoround6.8275totwodecimaldigits
9/23/16 Page 6
Calling Functions (2) • Theroundfunc0onreturnsitsresultbacktowherethefunc0onwascalledandyourprogramresumesexecu0on
9/23/16 Page 7
Function Arguments • Whenanotherfunc0oncallstheroundfunc0on,itprovides“inputs”,suchasthevalues6.8275and2inthecallround(6.8275,2)
• Thesevaluesarecalledtheargumentsofthefunc0oncall• Notethattheyarenotnecessarilyinputsprovidedbyahumanuser• Theyarethevaluesforwhichwewantthefunc0ontocomputearesult
9/23/16 Page 8
Function Arguments • Func0onscanreceivemul0pleargumentsoritisalsopossibletohavefunc0onswithnoarguments
9/23/16 Page 9
Function Return Values • The“output”thattheroundfunc0oncomputesiscalledthereturnvalue
• Func0onsreturnonlyonevalue• Thereturnvalueofafunc0onisreturnedtothepointinyourprogramwherethefunc0onwascalled
price=round(6.8275,2)
• Whentheroundfunc0onreturnsitsresult,thereturnvalueisstoredinthevariable‘price’statement)
9/23/16 Page 10
Function Return Values (2) • Donotconfusereturningavaluewithproducingprogramoutputwhichisproducedwhenusingaprint()statement
9/23/16 Page 11
Black Box Analogy • Athermostatisa‘blackbox’
• Setadesiredtemperature• Turnsonheater/ACasrequired• Youdon’thavetoknowhowitreallyworks!
• Howdoesitknowthecurrenttemp?• Whatsignals/commandsdoesitsendtotheheaterorA/C?
• Usefunc0onslike‘blackboxes’• Passthefunc0onwhatitneedstodoitsjob• Receivetheanswer
9/23/16 Page 12
The round Function as a Black Box • Youpasstheroundfunc0onitsnecessaryarguments(6.8275&2)anditproducesitsresult(6.83)
9/23/16 Page 13
The round Function as a Black Box • Youmaywonderhowtheroundfunc0onperformsitsjob
• Asauserofthefunc0on,youdon’tneedtoknowhowthefunc0onisimplemented
• Youjustneedtoknowthespecifica0onofthefunc0on:• Ifyouprovideargumentsxandn,thefunc0onreturnsxroundedtondecimaldigits
9/23/16 Page 14
Designing Your Own Functions • Whenyoudesignyourownfunc0ons,youwillwanttomakethemappearasblackboxestootherprogrammers• Evenifyouaretheonlypersonworkingonaprogram,makingeachfunc0onintoablackboxpaysoff:therearefewerdetailsthatyouneedtokeepinmind
9/23/16 Page 15
Implementing and Testing Functions SECTION 5.2
9/23/16 Page 16
Implementing and Testing Functions • Afunc0ontocalculatethevolumeofacube
• Whatdoesitneedtodoitsjob?• Whatdoesitanswerwith?
• Whenwri0ng(‘defining’)thisfunc0on• Pickanameforthefunc0on(cubeVolume)• Declareavariableforeachincomingargument(sideLength)(calledparametervariables)
• Putallthisinforma0ontogetheralongwiththedefkeywordtoformthefirstlineofthefunc0on’sdefini0on:
9/23/16 Page 17
defcubeVolume(sideLength):This line is called the header of the function
Testing a Function • Ifyourunaprogramcontainingjustthefunc0ondefini0on,thennothinghappens• Aferall,nobodyiscallingthefunc0on
• Inordertotestthefunc0on,yourprogramshouldcontain• Thedefini0onofthefunc0on• Statementsthatcallthefunc0onandprinttheresult
9/23/16 Page 18
Calling/Testing the Cube Function
defcubeVolume(sideLength):volume=sideLength**3returnvolume
result1=cubeVolume(2)result2=cubeVolume(10)print("Acubewithsidelength2hasvolume",result1)print("Acubewithsidelength10hasvolume",result2)
Implementing the function (function definition)
Calling/testing the function
9/23/16 Page 19
Syntax: Function Definition
9/23/16 Page 20
Programming Tip: Function Comments • Wheneveryouwriteafunc0on,youshouldcommentitsbehavior
• Remember,commentsareforhumanreaders,notcompilers(sortof)
##Computesthevolumeofacube.#@paramsideLengththelengthofasideofthecube#@returnthevolumeofthecube#defcubeVolume(sideLength):volume=sideLength**3returnvolume
Function comments explain the purpose of the function, the meaning of the parameter variables and the return value, as
well as any special requirements
9/23/16 Page 21
Cubes.py with Documentation
9/23/16 Page 22
Cubes.py • OpenthefileCubes.pyinPyCharm
• Thefilescontainstofunc0ons:• main• cubeVolume
• Line20containsthecalltothefunc0on“main”
9/23/16 Page 23
The main Function • Whendefiningandusingfunc0onsinPython,itisgoodprogrammingprac0cetoplaceallstatementsintofunc0ons,andtospecifyonefunc0onasthestar0ngpoint
• Anylegalnamecanbeusedforthestar0ngpoint,butwechose‘main’sinceitistherequiredfunc0onnameusedbyothercommonlanguages
• Ofcourse,wemusthaveonestatementintheprogramthatcallsthemainfunc0on
9/23/16 Page 24
Syntax: The main Function
9/23/16 Page 25
Using Functions: Order (1) • Itisimportantthatyoudefineanyfunc0onbeforeyoucallit
• Forexample,thefollowingwillproduceacompile-0meerror:
print(cubeVolume(10))defcubeVolume(sideLength):volume=sideLength**3returnvolume
• ThecompilerdoesnotknowthatthecubeVolumefunc0onwillbedefinedlaterintheprogram
9/23/16 Page 26
Using Functions: Order (2) • However,afunc0oncanbecalledfromwithinanotherfunc0onbeforetheformerhasbeendefined
• Thefollowingisperfectlylegal:defmain():result=cubeVolume(2)print("Acubewithsidelength2hasvolume",result)defcubeVolume(sideLength):volume=sideLength**3returnvolumemain()
9/23/16 Page 27
Parameter Passing SECTION 5.3
9/23/16 Page 28
Parameter Passing • Parametervariablesreceivetheargumentvaluessuppliedinthefunc0oncall
• Theargumentvaluemaybe:• Thecontentsofavariable• A‘literal’value(2)
• Aka,‘actualparameter’orargument
• Theparametervariableis:
• Declaredinthecalledfunc0on• Ini0alizedwiththevalueoftheargumentvalue
• Usedasavariableinsidethecalledfunc0on• Aka,‘formalparameter’
9/23/16 Page 29
Argument value
Parameter variable
out
Calledfunc0on
Callingfunc0on
in
Parameter Passing Steps result1=cubeVolume(2)
defcubeVolume(sideLength):volume=sideLength*3returnvolume
9/23/16 Page 30
Common Error 5.1 • Tryingtomodifyparametervariables
• Acopyoftheargumentvaluesispassed(theValueispassed)• Calledfunc0on(addTax)canmodifylocalcopy(price)
9/23/16 Page 31
defaddTax(price,rate):tax=price*rate/100#Noeffectoutsidethefunctionprice=price+taxreturntax;
total=10addTax(total,7.5);
10.0
10.75
total
price
copy
Programming Tip 5.2 • Donotmodifyparametervariables
deftotalCents(dollars,cents):cents=dollars*100+cents#Modifiesparametervariable.returncents
Manyprogrammersfindthisprac0ceconfusing
deftotalCents(dollars,cents):result=dollars*100+centsreturnresult
Toavoidtheconfusion,simplyintroduceaseparatevariable:
9/23/16 Page 32
Return Values SECTION 5.4
9/23/16 Page 33
Return Values • Func0onscan(op0onally)returnonevalue
• Addareturnstatementthatreturnsavalue
• Areturnstatementdoestwothings:1) Immediatelyterminatesthefunc0on
2) Passesthereturnvaluebacktothecallingfunc0on
9/23/16 Page 34
defcubeVolume(sideLength):volume=sideLength*3returnvolume
returnstatement
Thereturnvaluemaybeavalue,avariableoracalcula7on
Multiple return Statements • Afunc0oncanusemul0plereturnstatements
• Buteverybranchmusthaveareturnstatement
9/23/16 Page 35
defcubeVolume(sideLength):if(sideLength<0):return0returnsideLength*3
Multiple return Statements (2) • Alterna0vetomul0plereturns(e.g.,oneforeachbranch):
• Youcanavoidmul0plereturnsbystoringthefunc0onresultinavariablethatyoureturninthelaststatementofthefunc0on
• Forexample:
9/23/16 Page 36
defcubeVolume(sideLength):ifsideLength>=0:volume=sideLength**3else:volume=0returnvolume
Make Sure A Return Catches All Cases • Missingreturnstatement
• Makesureallcondi0onsarehandled• Inthiscase,sideLengthcouldbeequalto0
• Noreturnstatementforthiscondi0on• Thecompilerwillnotcomplainifanybranchhasnoreturnstatement
• Itmayresultinarun-0meerrorbecausePythonreturnsthespecialvalueNonewhenyouforgettoreturnavalue
9/23/16 Page 37
defcubeVolume(sideLength):ifsideLength>=0:returnsideLength**3#Error—noreturnvalueifsideLength<0
Make Sure A Return Catches All Cases (2)
• Acorrectimplementa0on:
9/23/16 Page 38
defcubeVolume(sideLength):ifsideLength>=0returnsideLength**3else:return0