31
Strings, Lists and Tuples Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

  • Upload
    others

  • View
    5

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Strings,ListsandTuplesIntrotoFunctions

CS8:IntroductiontoComputerScience,Winter2019Lecture#3

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

Page 2: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

AWordAboutRegistrationforCS8•  ThisclassisFULL, & thewaitlistisCLOSED.

1/14/19 Matni,CS8,Wi19 2

Page 3: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Administrative•  Lab01–tomorrow

•  Hw01–duetoday•  Hw02–duenextweek

•  Modificationstoclassschedule

•  Linuxworkshop•  PythonIDLE1/14/19 Matni,CS8,Wi19 3

Page 4: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

LectureOutline•  Strings&OperationsonStrings

•  IntrotoLists&Tuple

•  IntrotoFunctions

1/14/19 Matni,CS8,Wi19 4

Yellow Band = Class Demonstration! J

Page 5: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Strings•  Collectionofcharacters•  Astringliteralisenclosedinquotes–  Useeitherdouble-quotes(“)orsinglequotes(‘)

Examples: name="#JimboJones@UCSB?Wow!" nombre='LisaSimpson!!'

1/14/19 Matni,CS8,Wi19 5

Page 6: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

SpecialCharactersinStrings•  Whatwouldyoudoifyouwantedastringtobe: Isaid"hello!"

•  Answer:usethespecialcharacterindicator\–  Theback-slash

Example:message="Isaid\"hello!\""

1/14/19 Matni,CS8,Wi19 6Demo!

Page 7: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

StringsasObjects•  StringsareobjectsofaPythonclassnamedstr

•  Lotsofbuilt-infunctionsworkforstringobjects

•  Class=angeneral“blueprint”•  Object=aparticular“instant”ofaclass1/14/19 Matni,CS8,Wi18 7

Page 8: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

OperationsonStrings•  Concatenation

–  Mergingmultiplestringsinto1–  Usethe+operator

•  "saymy"+""+"name"willbecome"saymyname"

•  Repetition–  Easywaytomultiplythecontentsofastring–  Usethe*operator

•  "ja"*3is"jajaja”(whyisthereaspaceattheend?)

1/14/19 Matni,CS8,Wi18 8Demo!

Page 9: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Indexing•  Everycharacterinastringhasanindexassociatedwithit

•  InPython,indexingalwaysstartsat0.–  Sothe1stcharacterinthestringischaracter#0–  Indexingiscalledoutwithsquarebrackets[n]

1/14/19 Matni,CS8,Wi18 9

I ' m h e r e !

0 1 2 3 4 5 6 7 8

Page 10: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Indexing

•  Ifname="I'mhere!"then: name[0]="I" name[3]="" name[5]="e" name[15]isundefined(error)

1/14/19 Matni,CS8,Wi18 10

I ‘ m h e r e !

0 1 2 3 4 5 6 7 8

Page 11: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

IndicesandSlices•  Tosliceastringintoasmallerstring,use[i:j]– Wherei=startingindex,j=endingindex(NOTincluded)–  Example:"Gaucho"[2:4]is"uc"

•  Combinationsarepossible!–  Example,whatdoesthisspellout?(("o"+"Gaucho"[2:5]+"")*3)+"!"

1/14/19 Matni,CS8,Wi18 11

Page 12: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Exercise•  Whatisthevalueofsafterthefollowingcoderuns?

s='abc'

s='d'*3+ss=s+e*2

1/14/19 Matni,CS8,Wi19 12

A.‘abcd3e2’B.‘abcdddabc’C.‘dddabcee’D.‘abcdddabce2’E.Error

Page 13: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Lists•  Alistisacollectionofmultiplevalues

–  Similartohowastrisacollectionofcharacters

•  Note:InPython,listscanbeofheterogenous–  Ofdifferenttypes(i.e.intsorstringsoretc…)

•  Listscanalsohaveduplicatevalues•  Listsaremutable

–  Theelementsofalistcanbemodified1/14/19 Matni,CS8,Wi19 13

Page 14: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

ExampleofListsNameList=[“Abby”,“Bruce”,“Chris”]Student=[“JillJillson”,19,3.7,“F”]

NameListandStudentarevariablesoftypelist

•  YoucancalluplistelementsbyindexingthelistExample:NameList[0]=“Abby”Moreonlistslater…

1/14/19 Matni,CS8,Wi19 14

Page 15: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Tuples•  Tuplesareavariabletypethat’sverysimilartolists,

excepttheyareimmutable!–  Thatis,oncethey’reset,theycannotchange

•  Example:collection=(1,2,“bucklemyshoe”)

More(butnotmuchmore)ontupleslater…1/14/19 Matni,CS8,Wi19 15

Page 16: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Functions

1/14/19 Matni,CS8,Wi19 16

Page 17: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

ProceduralAbstraction:TheFunction•  A“blackbox”–apieceofcodethatcantakeinputsandgivesmesomeexpectedoutput

•  Afunction,forexample,isakindofproceduralabstraction 25àSquareRootFunctionà5

•  What’shappeninginsidethefunction?•  Doesn’tmatter,aslongasitworks!!

1/14/19 Matni,CS8,Wi19 17

Page 18: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Functions•  Afunctiondoes“something”toone/severalinput(s)andsendsbackone/severaloutput(s)– Alwayshasparenthesesto“carry”theinputs

•  Example:thesqrt()function(squareroot)– Withaninputof25,Iexpectanoutputof5–  Thatis,sqrt(25)willgiveme5

1/14/19 Matni,CS8,Wi19 18

Page 19: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

MoreAboutFunctions

1/14/19 Matni,CS8,Wi19 19

•  Definition:“Selfcontained”modulesofcodethataccomplishaspecifictask.

•  Functionshaveinputsthatgetprocessedandthefunctionoften(althoughnotalways)“returns”anoutput(result).

•  Functionscanbe“calledfrom”themainblockofaprogram–  Orfrominsideotherfunctions!

Page 20: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

MoreAboutFunctions

1/14/19 Matni,CS8,Wi19 20

•  Afunctioncanbeusedoverandoveragain.

•  Example:Considerafunctioncalled“distance”thatreturnsthevalueofthedistancebetweenapointw/coordinates(a,b)andtheCartesianorigin(0,0)

distance(a,b)=squarerootof(a2+b2)

Page 21: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

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/14/19 Matni,CS8,Wi19 21

Page 22: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

ExampleDefinition#Myfirstfunction!Yay!defdbl(x):

"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x #Ineedto“return”theresult

1/14/19 Matni,CS8,Wi19 22

Let’s try it out!

Page 23: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

FUNCTIONRULES!#Myfirstfunction!Yay!defdbl(x):

"""Thisfunctionreturnsdoubleitsinputx"""print(“Doublingthenumberto:”,x)return2*x #Ineedto“return”theresult

1/14/19 Matni,CS8,Wi19 23

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 24: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

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/14/19 Matni,CS8,Wi19 24

Let’s try it out!

Page 25: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

FlowofExecutionofaFunction•  Whenyoucallafunction,youhavetouseitsnameanditsparameter(s)

justliketheyweredefined–  Example:tocallthedblfunctionon21,you’dhavetocallitlikethis:

dbl(21)

•  Whenyoucallafunction,Pythonexecutesthefunctionstartingatthefirstlineinitsbody,andcarriesouteachlineinorder–  Thoughsomeinstructionscausetheordertochange…moresoon!

1/14/19 Matni,CS8,Wi19 25

Page 26: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

ParametersareSpecializedVariables•  Whenyoucallafunction,thevalueyouputinparenthesisgetsputintoaspecialpartofcomputermemorythat’slabeledwiththenameoftheparameterandisavailableforusewithinthefunction

•  Example:indbl(x),thevar.xcanbeusedseveraltimeswithinthatfunction

1/14/19 Matni,CS8,Wi19 26

Page 27: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

WhatifThereareMultipleParameters??

•  Whenyoucallafunction,thevaluesyouputinparenthesishavetobeintheorderinwhichtheyarelistedinthedefinition!

•  Example:defsubtract(m,n):returnm–n

1/14/19 Matni,CS8,Wi19 27

Whenyoucallthisfunctiontodoasubtractionof5–99,then:mhastobe5andnhastobe99

So,it’scalledas:subtract(5,99)i.e.notsubtract(99,5)

Page 28: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

WhatAbout…NOParameters?!•  Sure,youcandothat!

•  Example:deffortyTwo():return42

1/14/19 Matni,CS8,Wi19 28

Allthisfunctiondoesisreturnthenumber42towhoevercalledit!Whichwayshouldwecallit?

fortyTwofortyTwo()

Page 29: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

Wow.FunctionsareCool.CanTheyCALLEACHOTHER????

Yes!!!!!!!!!!!!!!!Carefulthatyougettheordercorrect…!

defhalve(x):"""returnshalfitsinput,x"""

returndiv(x,2)defdiv(y,x):"""returnsy/x"""

returny/xWhathappenswhenIsay:>>>halve(85)

1/14/19 Matni,CS8,Wi19 29

Let’s try it out!

A.  Iget42B.  Iget42.5C.  0D.  0.02352(i.e.,2dividedby85)

Page 30: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

YOURTO-DOsq  FinishreadingChapter2q  StartreadingChapter3q  StartonHW2(duenextMonday)q  DoLab1(lab’stomorrow!)

q  Embracerandomness

1/14/19 Matni,CS8,Wi18 30

Page 31: Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer Science, Winter 2019 Lecture #3 Ziad Matni, Ph.D. Dept. of Computer Science, UCSB

1/14/19 Matni,CS8,Wi18 31