return values...return values • func%ons can (op%onally) return one value • add a return...

35
Return Values SECTION 5.4 9/26/16 Page 33

Upload: others

Post on 13-Aug-2020

25 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Return Values SECTION 5.4

9/26/16 Page 33

Page 2: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Return Values •  Func%onscan(op%onally)returnonevalue

•  Addareturnstatementthatreturnsavalue

•  Areturnstatementdoestwothings:1)  Immediatelyterminatesthefunc%on

2)  Passesthereturnvaluebacktothecallingfunc%on

9/26/16 Page 34

defcubeVolume(sideLength):volume=sideLength*3returnvolume

returnstatement

Thereturnvaluemaybeavalue,avariableoracalcula3on

Page 3: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Multiple return Statements •  Afunc%oncanusemul%plereturnstatements

•  Buteverybranchmusthaveareturnstatement

9/26/16 Page 35

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

Page 4: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Multiple return Statements (2) •  Alterna%vetomul%plereturns(e.g.,oneforeachbranch):

•  Youcanavoidmul%plereturnsbystoringthefunc%onresultinavariablethatyoureturninthelaststatementofthefunc%on

•  Forexample:

9/26/16 Page 36

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

Page 5: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Make Sure A Return Catches All Cases •  Missingreturnstatement

•  Makesureallcondi%onsarehandled•  Inthiscase,sideLengthcouldbeequalto0

•  Noreturnstatementforthiscondi%on•  Thecompilerwillnotcomplainifanybranchhasnoreturnstatement

•  Itmayresultinarun-%meerrorbecausePythonreturnsthespecialvalueNonewhenyouforgettoreturnavalue

9/26/16 Page 37

defcubeVolume(sideLength):ifsideLength>=0:returnsideLength**3#Error—noreturnvalueifsideLength<0

Page 6: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Make Sure A Return Catches All Cases (2)

•  Acorrectimplementa%on:

9/26/16 Page 38

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

Page 7: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Implementing a Function: Steps 1.  Describewhatthefunc%onshoulddoi.  Provideasimple“liberalartsterms”descrip%onofwhatthe

func%onsdoesii.  “Computethevolumeofapyramidwithasquarebase”

2.  Determinealistofallofthefunc%onsinputsi.  Makealistofalloftheparametersthatcanvaryii.  Donotbeoverlyspecific

3.  Determinethetypesoftheparametervariablesandthereturnvalue

9/26/16 Page 39

Page 8: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Implementing a Function: Steps 4)  Writepseudocodeforobtainingthedesiredresulti.  Expressanmathema%calformulas,branchesandloopsin

pseudocode5)  Implementthefunc%onbody

9/26/16 Page 40

defpyramidVolume(height,baseLength):baseArea=baseLength*baseLengthreturnheight*baseArea/3

Page 9: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Implementing a Function: Steps

6)  Testyourfunc%oni.  Designtestcasesandcode

9/26/16 Page 41

Page 10: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Pyramids.py •  Openthefilepyramids.py

•  Lookathowthemainfunc%onissetuptomakethecallstopyramidVolumeandprinttheexpectedresults

9/26/16 Page 42

Page 11: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Functions Without Return Values SECTION 5.5

9/26/16 Page 43

Page 12: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Functions Without Return Values •  func%onsarenotrequiredtoreturnavalue

•  Noreturnstatementisrequired•  Thefunc%oncangenerateoutputevenwhenitdoesn’thaveareturnvalue

9/26/16 Page 44

defboxString(contents):n=len(contents):print("-"*(n+2))print("!"+contents+"!")print("-"*(n+2))

...boxString("Hello") ...

Page 13: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Using return Without a Value •  Youcanusethereturnstatementwithoutavalue

•  Thefunc%onwillterminateimmediately!

9/26/16 Page 45

defboxString(contents):n=len(contents)ifn==0:return#Returnimmediatelyprint("-"*(n+2))print("!"+contents+"!")print("-"*(n+2))

Page 14: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Reusable Functions SECTION 5.6

9/26/16 Page 46

Page 15: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Problem Solving: Reusable Functions

•  Findrepe++vecode•  Mayhavedifferentvaluesbutsamelogic

9/26/16 Page 47

hours=int(input("Enteravaluebetween0and23:"))whilehours<0orhours>23:print("Error:valueoutofrange.")hours=int(input("Enteravaluebetween0and23:"))minutes=int(input("Enteravaluebetween0and59:"))whileminutes<0orminutes>59:print("Error:valueoutofrange.")minutes=int(input("Enteravaluebetween0and59:"))

0-23

0-59

Page 16: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Write a ‘Parameterized’ Function ##Promptsausertoenteravalueuptoagivenmaximumuntiltheuserprovides#avalidinput.#@paramhighanintegerindicatingthelargestallowableinput#@returntheintegervalueprovidedbytheuser(between0andhigh,inclusive)#defreadIntUpTo(high):value=int(input("Enteravaluebetween0and"+str(high)+":"))whilevalue<0orvalue>high:print("Error:valueoutofrange.")value=int(input("Enteravaluebetween0and"+str(high)+":"))returnvalue

9/26/16 Page 48

Page 17: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Readtime.py •  Openthefileread%me.py

•  Testtheprogramwithseveralinputs•  HowwouldyoumodifyyourprojecttousethereadInBetweenfunc%on?

9/26/16 Page 49

Page 18: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

An Alternate If Structure •  Openthefileearthquake.py•  Thefilecontainstwofunc%onsthatsolvetheRichterscaleproblemfromearlierthissemester•  Thefirstusesan“if–elif”construct•  Thesecondusessingle-linecompoundstatements(SpecialTopic5.1,p.256)

•  Thisformofanifstatementisveryusefulinfunc%onsthatselectandreturnasinglevaluefromasetofvalues

9/26/16 Page 50

Page 19: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Stepwise Refinement SECTION 5.7

9/26/16 Page 51

Page 20: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Stepwise Refinement •  Tosolveadifficulttask,breakitdownintosimplertasks•  Thenkeepbreakingdownthesimplertasksintoevensimplerones,un%lyouareledwithtasksthatyouknowhowtosolve

9/26/16 Page 52

Page 21: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Get Coffee

•  Ifyoumustmakecoffee,therearetwoways:•  MakeInstantCoffee•  BrewCoffee

9/26/16 Page 53

Page 22: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Instant Coffee •  Twowaystoboilwater1)UseMicrowave2)UseKegleonStove

9/26/16 Page 54

Page 23: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Brew Coffee •  Assumescoffeemaker

•  Addwater•  Addfilter•  GrindCoffee

•  Addbeanstogrinder•  Grind60seconds

•  Fillfilterwithgroundcoffee•  Turncoffeemakeron

•  Stepsareeasilydone

9/26/16 Page 55

Page 24: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Stepwise Refinement Example •  Whenprin%ngacheck,itiscustomarytowritethecheckamountbothasanumber(“$274.15”)andasatextstring(“twohundredseventyfourdollarsand15cents”)

•  Writeaprogramtoturnanumberintoatextstring

•  Wow,soundsdifficult!

•  Breakitdown•  Let’stakethedollarpart(274)andcomeupwithaplan•  TakeanIntegerfrom0–999•  ReturnaString•  S%llpregyhard…

9/26/16 Page 56

Page 25: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Stepwise Refinement Example •  Takeitdigitbydigit(2,7,4)–ledtoright•  Handlethefirstdigit(hundreds)

•  Ifempty,wearedonewithhundreds•  Getfirstdigit(Integerfrom1–9)•  Getdigitname(“one”,“two”,“three”…)•  Addtheword“hundred”•  Soundseasy!

•  Seconddigit(tens)•  Getseconddigit(Integerfrom0–9)•  If0,wearedonewithtens…handlethirddigit•  If1,…maybeeleven,twelve...Teens…Noteasy!

•  Let’slookateachpossibilityled(1x-9x)…

9/26/16 Page 57

Page 26: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Stepwise Refinement Example •  Ifseconddigitisa0

•  Getthirddigit(Integerfrom0–9)•  Getdigitname(“”,“one”,“two”…)…Sameasbefore?•  Soundseasy!

•  Ifseconddigitisa1•  Getthirddigit(Integerfrom0–9)•  ReturnaString(“ten”,“eleven”,“twelve”…)

•  Ifseconddigitisa2-9•  Startwithstring“twenty”,“thirty”,“forty”…•  Getthirddigit(Integerfrom0–9)•  Getdigitname(“”,“one”,“two”…)…Sameasbefore•  Soundseasy!

9/26/16 Page 58

Page 27: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Name the Sub-Tasks •  digitName

•  TakesanIntegerfrom0–9•  ReturnaString(“”,“one”,“two”…)

•  tensName(seconddigit>=20)•  TakesanIntegerfrom0–9•  ReturnaString(“twenty”,“thirty”…)plus

•  digitName(thirddigit)•  teenName

•  TakesanIntegerfrom0–9•  ReturnaString(“ten”,“eleven”…)

9/26/16 Page 59

Page 28: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Write Pseudocode part=number(Thepartthats%llneedstobeconverted)name=“”(Thenameofthenumber)Ifpart>=100name=nameofhundredsinpart+"hundred"RemovehundredsfrompartIfpart>=20AppendtensName(part)tonameRemovetensfrompartElseifpart>=10AppendteenName(part)tonamepart=0If(part>0)AppenddigitName(part)toname

9/26/16 Page 60

Iden3fyfunc3onsthatwecanuse(orre-use!)todothework

Page 29: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Plan The Functions •  Decideonname,parameter(s)andtypesandreturntype

•  defintName(number):•  TurnsanumberintoitsEnglishname•  ReturnsaStringthatistheEnglishdescrip%onofanumber(e.g.,“sevenhundredtwentynine”)

•  defdigitName(digit):•  ReturnaString(“”,“one”,“two”…)

•  deftensName(number):•  ReturnaString(“twenty”,“thirty”…)plus

•  ReturnfromdigitName(thirdDigit)

•  defteenName(number):•  ReturnaString(“ten”,“eleven”…)

9/26/16 Page 61

Page 30: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Convert to Python: intName Function

•  Openthefileintname.pyinWing

•  maincallsintName•  Doesallthework•  ReturnsaString

•  Usesfunc%ons:•  tensName

•  teenName•  digitName

Page 62 9/26/16

Page 31: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

intName

Page 63 9/26/16

Page 32: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

digitName

9/26/16 Page 64

Page 33: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

teenName

9/26/16 Page 65

Page 34: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

tensName

9/26/16 Page 66

Page 35: Return Values...Return Values • Func%ons can (op%onally) return one value • Add a return statement that returns a value • A return statement does two things: 1) Immediately terminates

Programming Tips •  Keepfunc%onsshort

•  Ifmorethanonescreen,breakinto‘sub’func%ons•  Traceyourfunc%ons

•  Onelineforeachstep•  Columnsforkeyvariables

•  UseStubsasyouwritelargerprograms•  Unfinishedfunc%onsthatreturna‘dummy’value

9/26/16 Page 67