return values...return values • func%ons can (op%onally) return one value • add a return...
TRANSCRIPT
Return Values SECTION 5.4
9/26/16 Page 33
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
Multiple return Statements • Afunc%oncanusemul%plereturnstatements
• Buteverybranchmusthaveareturnstatement
9/26/16 Page 35
defcubeVolume(sideLength):if(sideLength<0):return0returnsideLength*3
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
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
Make Sure A Return Catches All Cases (2)
• Acorrectimplementa%on:
9/26/16 Page 38
defcubeVolume(sideLength):ifsideLength>=0returnsideLength**3else:return0
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
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
Implementing a Function: Steps
6) Testyourfunc%oni. Designtestcasesandcode
9/26/16 Page 41
Pyramids.py • Openthefilepyramids.py
• Lookathowthemainfunc%onissetuptomakethecallstopyramidVolumeandprinttheexpectedresults
9/26/16 Page 42
Functions Without Return Values SECTION 5.5
9/26/16 Page 43
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") ...
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))
Reusable Functions SECTION 5.6
9/26/16 Page 46
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
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
Readtime.py • Openthefileread%me.py
• Testtheprogramwithseveralinputs• HowwouldyoumodifyyourprojecttousethereadInBetweenfunc%on?
9/26/16 Page 49
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
Stepwise Refinement SECTION 5.7
9/26/16 Page 51
Stepwise Refinement • Tosolveadifficulttask,breakitdownintosimplertasks• Thenkeepbreakingdownthesimplertasksintoevensimplerones,un%lyouareledwithtasksthatyouknowhowtosolve
9/26/16 Page 52
Get Coffee
• Ifyoumustmakecoffee,therearetwoways:• MakeInstantCoffee• BrewCoffee
9/26/16 Page 53
Instant Coffee • Twowaystoboilwater1)UseMicrowave2)UseKegleonStove
9/26/16 Page 54
Brew Coffee • Assumescoffeemaker
• Addwater• Addfilter• GrindCoffee
• Addbeanstogrinder• Grind60seconds
• Fillfilterwithgroundcoffee• Turncoffeemakeron
• Stepsareeasilydone
9/26/16 Page 55
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
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
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
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
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
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
Convert to Python: intName Function
• Openthefileintname.pyinWing
• maincallsintName• Doesallthework• ReturnsaString
• Usesfunc%ons:• tensName
• teenName• digitName
Page 62 9/26/16
intName
Page 63 9/26/16
digitName
9/26/16 Page 64
teenName
9/26/16 Page 65
tensName
9/26/16 Page 66
Programming Tips • Keepfunc%onsshort
• Ifmorethanonescreen,breakinto‘sub’func%ons• Traceyourfunc%ons
• Onelineforeachstep• Columnsforkeyvariables
• UseStubsasyouwritelargerprograms• Unfinishedfunc%onsthatreturna‘dummy’value
9/26/16 Page 67