25
More About Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #4 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

MoreAboutFunctions

CS8:IntroductiontoComputerScience,Winter2019Lecture#4

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

AWordAboutRegistrationforCS8•  ThisclassisFULL, & thewaitlistisCLOSED.

1/16/19 Matni,CS8,Wi19 2

Page 3: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

Administrative•  Lab01–dueFriday(makesureyoursubmissionisonthere)

•  Hw02–duenextweekonWEDNESDAY–  Becausethere’snoschoolnextMonday…

•  Linuxworkshoprepeatthis

Friday@10AM(Phelps2510)1/16/19 Matni,CS8,Wi19 3

Page 4: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

LectureOutline•  Strings&OperationsonStrings

•  IntrotoLists&Tuple

•  IntrotoFunctions

1/16/19 Matni,CS8,Wi19 4

Yellow Band = Class Demonstration! J

Page 5: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 6: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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!

Page 7: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 8: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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!

Page 9: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 10: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

FlowofExecutionofaFunctionWhenyoucallafunction,Pythonexecutesitstartingatthefirstlineinitsbody,andcarriesouteachlineinorderThoughsomeinstructionscancausetheordertochange

…moresoon!

1/16/19 Matni,CS8,Wi19 10

defdbl(x):"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x

Page 11: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

LocalvsGlobalVariables•  AglobalvariableisdefinedEVERYWHEREintheprogram

•  Alocalvariableisdefinedwithinsomespecificconfinesofacomputerprogram–  i.e.noteverywhereintheprogram

1/16/19 Matni,CS8,Wi19 11

Page 12: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 13: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 14: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 15: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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

Page 16: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

Built-In(Fun)ctionsforStrings•  Lengthofstring:len(string)–  Example:len("GauchoGreg")is11

•  Considerastringcalledst3andthatlen(st3)=7– WhatistheindexoftheLASTcharacterinst3?

1/16/19 Matni,CS8,Wi18 16

Page 17: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

More(Fun)ctions!•  Booleanoperatorsinandnotinaregreatwaystocheckifasub-stringisfoundinsidealongerstring

Examples:•  “fun”in“functions” =•  “fun”in“Functions” =•  “Fan”notin“Functions”=1/16/19 Matni,CS8,Wi18 17

True

TrueFalse

Page 18: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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!

Page 19: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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)

Page 20: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

WhatAbout…NOParameters?!•  Sure,youcandothat! Butyoustillneedtheparentheses!

•  Example:deffortyTwo():return42

1/16/19 Matni,CS8,Wi19 20

Allthisfunctiondoesisreturnthenumber42towhoevercalledit!Whichwayshouldwecallit?

fortyTwofortyTwo()

Let’s try it out!

Page 21: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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)

Page 22: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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!

Page 23: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

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!

Page 24: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

YOURTO-DOsq  StartreadingChapter3q  StartonHW2(duenextWednesday)q  DoLab1(turnitinbyFriday)

q  Embracerandomness

1/16/19 Matni,CS8,Wi18 24

Page 25: More About Functions - GitHub Pages• name.count(‘ubb’) is 1 ß counts how many times ‘ubb’ occurs • name.ljust(9) is ‘Bubba ’ ß left justifies name in 9 spaces •

1/16/19 Matni,CS8,Wi18 25