chapter five: functions · 2016-09-26 · ch05.pptx author: donald patterson created date:...

38
Chapter Five: Functions

Upload: others

Post on 13-Aug-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Chapter Five: Functions

Page 2: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Chapter Goals •  Tobeabletoimplementfunc0ons•  Tobecomefamiliarwiththeconceptofparameterpassing•  Todevelopstrategiesfordecomposingcomplextasksintosimplerones•  Tobeabletodeterminethescopeofavariable•  Tolearnhowtothinkrecursively

Inthischapter,youwilllearnhowtodesignandimplementyourownfunc7ons

Usingtheprocessofstepwiserefinement,youwillbeabletobreakupcomplextasksintosetsofcoopera7ngfunc7ons

9/23/16 Page 2

Page 3: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Contents •  Func0onsasBlackBoxes•  Implemen0ngandTes0ngFunc0ons•  ParameterPassing•  ReturnValues•  Func0onswithoutReturnValues•  ReusableFunc0ons•  StepwiseRefinement•  VariableScope•  Graphics:BuildinganImageProcessingToolkit•  RecursiveFunc0ons

9/23/16 Page 3

Page 4: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Functions as Black Boxes SECTION 5.1

9/23/16 Page 4

Page 5: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Functions as Black Boxes •  Afunc0onisasequenceofinstruc0onswithaname

•  Forexample,theroundfunc0on,whichwasintroducedinChapter2,containsinstruc0onstoroundafloa0ng-pointvaluetoaspecifiednumberofdecimalplaces

9/23/16 Page 5

Page 6: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Calling Functions •  Youcallafunc0oninordertoexecuteitsinstruc0onsprice=round(6.8275,2)#Setsresultto6.83

•  Byusingtheexpressionround(6.8275,2),yourprogramcallstheroundfunc0on,askingittoround6.8275totwodecimaldigits

9/23/16 Page 6

Page 7: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Calling Functions (2) •  Theroundfunc0onreturnsitsresultbacktowherethefunc0onwascalledandyourprogramresumesexecu0on

9/23/16 Page 7

Page 8: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Function Arguments •  Whenanotherfunc0oncallstheroundfunc0on,itprovides“inputs”,suchasthevalues6.8275and2inthecallround(6.8275,2)

•  Thesevaluesarecalledtheargumentsofthefunc0oncall•  Notethattheyarenotnecessarilyinputsprovidedbyahumanuser•  Theyarethevaluesforwhichwewantthefunc0ontocomputearesult

9/23/16 Page 8

Page 9: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Function Arguments •  Func0onscanreceivemul0pleargumentsoritisalsopossibletohavefunc0onswithnoarguments

9/23/16 Page 9

Page 10: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Function Return Values •  The“output”thattheroundfunc0oncomputesiscalledthereturnvalue

•  Func0onsreturnonlyonevalue•  Thereturnvalueofafunc0onisreturnedtothepointinyourprogramwherethefunc0onwascalled

price=round(6.8275,2)

•  Whentheroundfunc0onreturnsitsresult,thereturnvalueisstoredinthevariable‘price’statement)

9/23/16 Page 10

Page 11: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Function Return Values (2) •  Donotconfusereturningavaluewithproducingprogramoutputwhichisproducedwhenusingaprint()statement

9/23/16 Page 11

Page 12: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Black Box Analogy •  Athermostatisa‘blackbox’

•  Setadesiredtemperature•  Turnsonheater/ACasrequired•  Youdon’thavetoknowhowitreallyworks!

•  Howdoesitknowthecurrenttemp?•  Whatsignals/commandsdoesitsendtotheheaterorA/C?

•  Usefunc0onslike‘blackboxes’•  Passthefunc0onwhatitneedstodoitsjob•  Receivetheanswer

9/23/16 Page 12

Page 13: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

The round Function as a Black Box •  Youpasstheroundfunc0onitsnecessaryarguments(6.8275&2)anditproducesitsresult(6.83)

9/23/16 Page 13

Page 14: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

The round Function as a Black Box •  Youmaywonderhowtheroundfunc0onperformsitsjob

•  Asauserofthefunc0on,youdon’tneedtoknowhowthefunc0onisimplemented

•  Youjustneedtoknowthespecifica0onofthefunc0on:•  Ifyouprovideargumentsxandn,thefunc0onreturnsxroundedtondecimaldigits

9/23/16 Page 14

Page 15: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Designing Your Own Functions •  Whenyoudesignyourownfunc0ons,youwillwanttomakethemappearasblackboxestootherprogrammers•  Evenifyouaretheonlypersonworkingonaprogram,makingeachfunc0onintoablackboxpaysoff:therearefewerdetailsthatyouneedtokeepinmind

9/23/16 Page 15

Page 16: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Implementing and Testing Functions SECTION 5.2

9/23/16 Page 16

Page 17: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 18: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Testing a Function •  Ifyourunaprogramcontainingjustthefunc0ondefini0on,thennothinghappens•  Aferall,nobodyiscallingthefunc0on

•  Inordertotestthefunc0on,yourprogramshouldcontain•  Thedefini0onofthefunc0on•  Statementsthatcallthefunc0onandprinttheresult

9/23/16 Page 18

Page 19: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 20: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Syntax: Function Definition

9/23/16 Page 20

Page 21: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 22: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Cubes.py with Documentation

9/23/16 Page 22

Page 23: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Cubes.py •  OpenthefileCubes.pyinPyCharm

•  Thefilescontainstofunc0ons:•  main•  cubeVolume

•  Line20containsthecalltothefunc0on“main”

9/23/16 Page 23

Page 24: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

The main Function •  Whendefiningandusingfunc0onsinPython,itisgoodprogrammingprac0cetoplaceallstatementsintofunc0ons,andtospecifyonefunc0onasthestar0ngpoint

•  Anylegalnamecanbeusedforthestar0ngpoint,butwechose‘main’sinceitistherequiredfunc0onnameusedbyothercommonlanguages

•  Ofcourse,wemusthaveonestatementintheprogramthatcallsthemainfunc0on

9/23/16 Page 24

Page 25: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Syntax: The main Function

9/23/16 Page 25

Page 26: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Using Functions: Order (1) •  Itisimportantthatyoudefineanyfunc0onbeforeyoucallit

•  Forexample,thefollowingwillproduceacompile-0meerror:

print(cubeVolume(10))defcubeVolume(sideLength):volume=sideLength**3returnvolume

•  ThecompilerdoesnotknowthatthecubeVolumefunc0onwillbedefinedlaterintheprogram

9/23/16 Page 26

Page 27: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Using Functions: Order (2) •  However,afunc0oncanbecalledfromwithinanotherfunc0onbeforetheformerhasbeendefined

•  Thefollowingisperfectlylegal:defmain():result=cubeVolume(2)print("Acubewithsidelength2hasvolume",result)defcubeVolume(sideLength):volume=sideLength**3returnvolumemain()

9/23/16 Page 27

Page 28: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Parameter Passing SECTION 5.3

9/23/16 Page 28

Page 29: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 30: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Parameter Passing Steps result1=cubeVolume(2)

defcubeVolume(sideLength):volume=sideLength*3returnvolume

9/23/16 Page 30

Page 31: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 32: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 33: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Return Values SECTION 5.4

9/23/16 Page 33

Page 34: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Return Values •  Func0onscan(op0onally)returnonevalue

•  Addareturnstatementthatreturnsavalue

•  Areturnstatementdoestwothings:1)  Immediatelyterminatesthefunc0on

2)  Passesthereturnvaluebacktothecallingfunc0on

9/23/16 Page 34

defcubeVolume(sideLength):volume=sideLength*3returnvolume

returnstatement

Thereturnvaluemaybeavalue,avariableoracalcula7on

Page 35: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Multiple return Statements •  Afunc0oncanusemul0plereturnstatements

•  Buteverybranchmusthaveareturnstatement

9/23/16 Page 35

defcubeVolume(sideLength):if(sideLength<0):return0returnsideLength*3

Page 36: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Multiple return Statements (2) •  Alterna0vetomul0plereturns(e.g.,oneforeachbranch):

•  Youcanavoidmul0plereturnsbystoringthefunc0onresultinavariablethatyoureturninthelaststatementofthefunc0on

•  Forexample:

9/23/16 Page 36

defcubeVolume(sideLength):ifsideLength>=0:volume=sideLength**3else:volume=0returnvolume

Page 37: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

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

Page 38: Chapter Five: Functions · 2016-09-26 · ch05.pptx Author: Donald Patterson Created Date: 9/26/2016 2:49:19 AM

Make Sure A Return Catches All Cases (2)

•  Acorrectimplementa0on:

9/23/16 Page 38

defcubeVolume(sideLength):ifsideLength>=0returnsideLength**3else:return0