Strings, Lists and Tuples Intro to Functions · Intro to Functions CS 8: Introduction to Computer...

Preview:

Citation preview

Strings,ListsandTuplesIntrotoFunctions

CS8:IntroductiontoComputerScience,Winter2019Lecture#3

ZiadMatni,Ph.D.

Dept.ofComputerScience,UCSB

AWordAboutRegistrationforCS8•  ThisclassisFULL, & thewaitlistisCLOSED.

1/14/19 Matni,CS8,Wi19 2

Administrative•  Lab01–tomorrow

•  Hw01–duetoday•  Hw02–duenextweek

•  Modificationstoclassschedule

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

LectureOutline•  Strings&OperationsonStrings

•  IntrotoLists&Tuple

•  IntrotoFunctions

1/14/19 Matni,CS8,Wi19 4

Yellow Band = Class Demonstration! J

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

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

1/14/19 Matni,CS8,Wi19 5

SpecialCharactersinStrings•  Whatwouldyoudoifyouwantedastringtobe: Isaid"hello!"

•  Answer:usethespecialcharacterindicator\–  Theback-slash

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

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

StringsasObjects•  StringsareobjectsofaPythonclassnamedstr

•  Lotsofbuilt-infunctionsworkforstringobjects

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

OperationsonStrings•  Concatenation

–  Mergingmultiplestringsinto1–  Usethe+operator

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

•  Repetition–  Easywaytomultiplythecontentsofastring–  Usethe*operator

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

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

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

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

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

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

Lists•  Alistisacollectionofmultiplevalues

–  Similartohowastrisacollectionofcharacters

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

•  Listscanalsohaveduplicatevalues•  Listsaremutable

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

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

NameListandStudentarevariablesoftypelist

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

1/14/19 Matni,CS8,Wi19 14

Tuples•  Tuplesareavariabletypethat’sverysimilartolists,

excepttheyareimmutable!–  Thatis,oncethey’reset,theycannotchange

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

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

Functions

1/14/19 Matni,CS8,Wi19 16

ProceduralAbstraction:TheFunction•  A“blackbox”–apieceofcodethatcantakeinputsandgivesmesomeexpectedoutput

•  Afunction,forexample,isakindofproceduralabstraction 25àSquareRootFunctionà5

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

1/14/19 Matni,CS8,Wi19 17

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

MoreAboutFunctions

1/14/19 Matni,CS8,Wi19 19

•  Definition:“Selfcontained”modulesofcodethataccomplishaspecifictask.

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

•  Functionscanbe“calledfrom”themainblockofaprogram–  Orfrominsideotherfunctions!

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)

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

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!

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

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!

FlowofExecutionofaFunction•  Whenyoucallafunction,youhavetouseitsnameanditsparameter(s)

justliketheyweredefined–  Example:tocallthedblfunctionon21,you’dhavetocallitlikethis:

dbl(21)

•  Whenyoucallafunction,Pythonexecutesthefunctionstartingatthefirstlineinitsbody,andcarriesouteachlineinorder–  Thoughsomeinstructionscausetheordertochange…moresoon!

1/14/19 Matni,CS8,Wi19 25

ParametersareSpecializedVariables•  Whenyoucallafunction,thevalueyouputinparenthesisgetsputintoaspecialpartofcomputermemorythat’slabeledwiththenameoftheparameterandisavailableforusewithinthefunction

•  Example:indbl(x),thevar.xcanbeusedseveraltimeswithinthatfunction

1/14/19 Matni,CS8,Wi19 26

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)

WhatAbout…NOParameters?!•  Sure,youcandothat!

•  Example:deffortyTwo():return42

1/14/19 Matni,CS8,Wi19 28

Allthisfunctiondoesisreturnthenumber42towhoevercalledit!Whichwayshouldwecallit?

fortyTwofortyTwo()

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)

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

q  Embracerandomness

1/14/19 Matni,CS8,Wi18 30

1/14/19 Matni,CS8,Wi18 31

Recommended