Upload
others
View
0
Download
0
Embed Size (px)
Citation preview
MoreAboutFunctions
CS8:IntroductiontoComputerScience,Winter2019Lecture#4
ZiadMatni,Ph.D.
Dept.ofComputerScience,UCSB
AWordAboutRegistrationforCS8• ThisclassisFULL, & thewaitlistisCLOSED.
1/16/19 Matni,CS8,Wi19 2
Administrative• Lab01–dueFriday(makesureyoursubmissionisonthere)
• Hw02–duenextweekonWEDNESDAY– Becausethere’snoschoolnextMonday…
• Linuxworkshoprepeatthis
Friday@10AM(Phelps2510)1/16/19 Matni,CS8,Wi19 3
LectureOutline• Strings&OperationsonStrings
• IntrotoLists&Tuple
• IntrotoFunctions
1/16/19 Matni,CS8,Wi19 4
Yellow Band = Class Demonstration! J
DefiningYourOwnFunction• TodefineafunctioninPython,thesyntaxis: def functionName (list of parameters): # a block of statements appear here
# all of them must be indented (with tabs)
– def –amandatorykeywordthatdefinesafunction– functionName –anylegalPythonidentifier(e.g.myLittleFunction)– ( ):–mandatorysetofparenthesesandcolon– list of parameters –objectnames
• Localreferencestoobjects(i.e.rawdataorvariables)thatarepassedintothefunction– e.g.def myLittleFunction(pony1, pony2, 3.1415):
1/16/19 Matni,CS8,Wi19 5
ExampleDefinition#Myfirstfunction!Yay!defdbl(x):
"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x #Ineedto“return”theresult
1/16/19 Matni,CS8,Wi19 6
Let’s try it out!
FUNCTIONRULES!#Myfirstfunction!Yay!defdbl(x):
"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x #Ineedto“return”theresult
1/16/19 Matni,CS8,Wi19 7
Function header x is the input parameter (also called argument)
docstring: a comment that becomes part of Python's built-in help system! With each function be sure to include one that: a) describes overall what the function does, and b) explains what the inputs mean/are
Function body
Indentation: VERY IMPORTANT Achieved with a tab character or just spaces All the lines in the function body are indented from the function header, and all to the same degree
MoreExampleDefinitions#Thisfunctioncalculatesthedistancebetween(a,b)and(0,0)defdistance(a,b):
x=a**2 #Notethetabindent!!!y=b**2 #Recall**means“tothepowerof”z=(x+y)**0.5returnz #Ineedto“return”theresult
!!!Alternatively!!!
defdistance(a,b):return((a**2)+(b**2))**0.5
1/16/19 Matni,CS8,Wi19 8
Let’s try it out!
FlowofExecutionofaFunction
Whenyoucallafunction,youhavetouseitsnameanditsparameter(s)justliketheyweredefinedExample:tocallthedblfunctionon21,you’dhavetocallitlikethis:
dbl(21)
1/16/19 Matni,CS8,Wi19 9
defdbl(x):"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x
FlowofExecutionofaFunctionWhenyoucallafunction,Pythonexecutesitstartingatthefirstlineinitsbody,andcarriesouteachlineinorderThoughsomeinstructionscancausetheordertochange
…moresoon!
1/16/19 Matni,CS8,Wi19 10
defdbl(x):"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x
LocalvsGlobalVariables• AglobalvariableisdefinedEVERYWHEREintheprogram
• Alocalvariableisdefinedwithinsomespecificconfinesofacomputerprogram– i.e.noteverywhereintheprogram
1/16/19 Matni,CS8,Wi19 11
ParametersareSpecializedVariables
Whenyoucallafunction,thevalueyouputinparenthesisgetsputintoaspecialpartofcomputermemorythat’slabeledwiththenameoftheparameterandisavailableforusewithinthefunction
Example:indbl(x),thevar.xcanbeusedseveraltimeswithinthatfunctionBUT!Itcan’tbeusedoutsideofthedbl()function
That’sbecausexisconsideredlocaltodbl()1/16/19 Matni,CS8,Wi19 12
defdbl(x):"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x
WhichoftheFollowingContainsaFunctionCall?
1) type(4.5)2) defdbl(x):
return2*x
3) area(2,9)4) print("Hello")
1/16/19 Matni,CS8,Wi19 13
A.(3)onlyB.(2)and(3)C.(1),(3),and(4)D.Allofthemincludeafunctioncall
Whatis/aretheBug(s)intheFollowingCode?
defdbl(x):return2*xy=2x=5dbl(y)print(x,y,dbl(y))
1/16/19 Matni,CS8,Wi19 14
A. Nobugs.ThecodeisfineB. Thefunctionbodyisnot
indentedC. Wearereferringtox
outsidethedefinitionofthefunction
D. BothBandCarebugs
Globalvs.LocalVariables:WhatistheOutputofthisCode?
defdbl(x):return2*x
y=2x=5x=dbl(y)print(x,y,dbl(y))
1/16/19 Matni,CS8,Wi19 15
A. 1048B. 524C. 1024D. Noneoftheabove
Built-In(Fun)ctionsforStrings• Lengthofstring:len(string)– Example:len("GauchoGreg")is11
• Considerastringcalledst3andthatlen(st3)=7– WhatistheindexoftheLASTcharacterinst3?
1/16/19 Matni,CS8,Wi18 16
More(Fun)ctions!• Booleanoperatorsinandnotinaregreatwaystocheckifasub-stringisfoundinsidealongerstring
Examples:• “fun”in“functions” =• “fun”in“Functions” =• “Fan”notin“Functions”=1/16/19 Matni,CS8,Wi18 17
True
TrueFalse
StringMethodsAssume:name=‘Bubba’
• name.center(9)is ‘Bubba’ ßcentersw/spacesoneachside• name.count(‘b’)is 2 ßcountshowmanytimes‘b’occurs
• name.count(‘ubb’)is1 ßcountshowmanytimes‘ubb’occurs• name.ljust(9)is ‘Bubba’ ßleftjustifiesnamein9spaces
• name.rjust(9)is ‘Bubba’ ßrightjustifiesnamein9spaces• name.upper()is ‘BUBBA’ ßalluppercaseletters• name.lower()is ‘bubba’ ßalllowercaseletters
• name.index(‘bb’)is 2 ßIndexoffirstoccurrenceoffirstletter• name.find(‘bb’)is 2 ßIndexoffirstoccurrenceoffirstletter• name.find(‘z’)is –1 ifnotfound,thenreturns-1• name.replace(‘bb’,‘dd’)is‘Budda’ ßReplacesonesub-stringforanother
1/16/19 Matni,CS8,Wi18 18
Tryalloftheseout!Amethodislikeafunctionthat’sbuilt-inforaclass(likestr)
Theyareusedwiththe“dotoperator”
Let’s try (some of these) out!
WhatifThereareMultipleParameters??
• Whenyoucallafunction,thevaluesyouputinparenthesishavetobeintheorderinwhichtheyarelistedinthedefinition!
• Example:defsubtract(m,n):returnm–n
1/16/19 Matni,CS8,Wi19 19
Whenyoucallthisfunctiontodoasubtractionof5–99,then:mhastobe5andnhastobe99
So,it’scalledas:subtract(5,99)i.e.notsubtract(99,5)
WhatAbout…NOParameters?!• Sure,youcandothat! Butyoustillneedtheparentheses!
• Example:deffortyTwo():return42
1/16/19 Matni,CS8,Wi19 20
Allthisfunctiondoesisreturnthenumber42towhoevercalledit!Whichwayshouldwecallit?
fortyTwofortyTwo()
Let’s try it out!
Wow.FunctionsareCool.CanTheyCALLEACHOTHER????
Yes!!!!!!!!!!!!!!!Carefulthatyougettheordercorrect…!
defhalve(x):"""returnshalfitsinput,x"""
returndiv(x,2)defdiv(y,x):"""returnsy/x"""
returny/xWhathappenswhenIsay:>>>halve(85)
1/16/19 Matni,CS8,Wi19 21
Let’s try it out!
A. Iget42B. Iget42.5C. 0D. 0.02352(i.e.,2dividedby85)
AFunctionisaFunctionisaFunction• Afunctioncanbeuser-definedorcanbebuilt-intoPythonmodules
andclasses
Example:print() isabuilt-inPythoncorefunctionthatcanbeused inseveralways(DEMO!)
sum()max() arebuilt-inPythoncorefunctionsthatcanbeusedmin() withlists(DEMO!)
1/16/19 Matni,CS8,Wi19 22Let’s try it out!
PythonModules• Pythonisopen-sourced:Thereare10,000sofready-mademodulestouse!• Popularonesinclude:
– math hasbasicmath/trigfunctionslikesqrt(),sin(),cos(),pow()– fractions introducesthefractiontypeofvar– turtle apopulargraphic/drawingmodule
• Everytimeyouwanttouseamoduleyouhavetoimportitfirst– Example: importmath
• Everytimeyouwanttouseafunctionthat’sinthemoduleyouhavetousethedotoperator– Example: a=math.sqrt(5)#acontainsthesquare-rootof5
1/16/19 Matni,CS8,Wi19 23Let’s try it out!
YOURTO-DOsq StartreadingChapter3q StartonHW2(duenextWednesday)q DoLab1(turnitinbyFriday)
q Embracerandomness
1/16/19 Matni,CS8,Wi18 24
1/16/19 Matni,CS8,Wi18 25