1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 7: Python’s Built-in Types and Basic Statements COMP 144 Programming Language Concepts

Download 1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 7: Python’s Built-in Types and Basic Statements COMP 144 Programming Language Concepts

Post on 22-Dec-2015

214 views

Category:

Documents

0 download

Embed Size (px)

TRANSCRIPT

<ul><li> Slide 1 </li> <li> 1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 7: Pythons Built-in Types and Basic Statements COMP 144 Programming Language Concepts Spring 2002 Felix Hernandez-Campos Jan 25 The University of North Carolina at Chapel Hill </li> <li> Slide 2 </li> <li> 2 COMP 144 Programming Language Concepts Felix Hernandez-Campos Built-in Data Structures: Lists A list is an ordered collection of objectsA list is an ordered collection of objects Lists can contain any type of objectLists can contain any type of object Lists are mutableLists are mutable ExamplesExamples [] Empty list [1, 2, 3.0] Three-element list [1, [2, 4], 3.0] Nested list </li> <li> Slide 3 &gt;&gt; l[0] 1 &gt;&gt;&gt; l[2] 3.0 &gt;&gt;&gt; l[1] ['2', 4] &gt;&gt;&gt; l[3] = 4 Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? l[3] = 4 l[3] = 4 IndexError: list assignment index out of range"&gt; </li><li> 3 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Accessing Items Syntax: list[index]Syntax: list[index] Indexing from the left starts at 0 E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; l[0] 1 &gt;&gt;&gt; l[2] 3.0 &gt;&gt;&gt; l[1] ['2', 4] &gt;&gt;&gt; l[3] = 4 Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? l[3] = 4 l[3] = 4 IndexError: list assignment index out of range </li> <li> Slide 4 &gt;&gt; l[-1] 3.0 &gt;&gt;&gt; l[-3] 1 &gt;&gt;&gt; l[-4] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? l[-4] l[-4] IndexError: list index out of range"&gt; </li><li> 4 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Accessing Items Syntax: list[-index]Syntax: list[-index] Indexing from the right starts at -1 E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; l[-1] 3.0 &gt;&gt;&gt; l[-3] 1 &gt;&gt;&gt; l[-4] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? l[-4] l[-4] IndexError: list index out of range </li> <li> Slide 5 &gt;&gt; del l[2] &gt;&gt;&gt; l [1, ['2', 4]] &gt;&gt;&gt; del l[2] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? del l[2] del l[2] IndexError: list assignment index out of range"&gt; </li><li> 5 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Deleting Items Syntax: del list[index]Syntax: del list[index] E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; del l[2] &gt;&gt;&gt; l [1, ['2', 4]] &gt;&gt;&gt; del l[2] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? del l[2] del l[2] IndexError: list assignment index out of range </li> <li> Slide 6 &gt;&gt; "&gt; &gt;&gt; len(l) 3 &gt;&gt;&gt; l = [] &gt;&gt;&gt; len(l) 0"&gt; &gt;&gt; " title="6 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Length Syntax: len(list)Syntax: len(list) E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; "&gt; </li><li> 6 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Length Syntax: len(list)Syntax: len(list) E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; len(l) 3 &gt;&gt;&gt; l = [] &gt;&gt;&gt; len(l) 0 </li> <li> Slide 7 </li> <li> 7 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Constructing Lists ConcatenationConcatenation Syntax: list1 + list2 E.g. &gt;&gt;&gt; l1 = [1, 2] &gt;&gt;&gt; l1 + [3, 4, 5] [1, 2, 3, 4, 5] RepetitionRepetition Syntax: list * integer E.g. &gt;&gt;&gt; [1, 2] * 5 [1, 2, 1, 2, 1, 2, 1, 2, 1, 2] </li> <li> Slide 8 &gt;&gt; l[1:2] [['2', 4]] &gt;&gt;&gt; l[0:-2] [1] &gt;&gt;&gt; l[1:-2] [] &gt;&gt;&gt; l[1:-3] [] &gt;&gt;&gt; l[1:3] = [2, 3] &gt;&gt;&gt; l [1, 2, 3]"&gt; &gt;&gt; l = [1, ["2", 4]"&gt; </li><li> 8 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Constructing Lists SlicingSlicing Syntax: list[i:j] E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; l[1:2] [['2', 4]] &gt;&gt;&gt; l[0:-2] [1] &gt;&gt;&gt; l[1:-2] [] &gt;&gt;&gt; l[1:-3] [] &gt;&gt;&gt; l[1:3] = [2, 3] &gt;&gt;&gt; l [1, 2, 3] </li> <li> Slide 9 </li> <li> 9 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Constructing Lists RangesRanges Syntax: range(start, end, step) Default values for start (0) and step (1) E.g. &gt;&gt;&gt; range(1,100,10) [1, 11, 21, 31, 41, 51, 61, 71, 81, 91] &gt;&gt;&gt; range(1,13) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] &gt;&gt;&gt; range(3) [0, 1, 2] </li> <li> Slide 10 &gt;&gt; l.insert(0, 8.3) &gt;&gt;&gt; l [8.3, 1, ['2', 4], 3.0] Adding an item at the end of the listAdding an item at the end of the list Syntax: list.append[item] E.g. &gt;&gt;&gt; l.append(end) &gt;&gt;&gt; l [8.3, 1, ['2', 4], 3.0, end]"&gt; </li><li> 10 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Methods Inserting an item at a given positionInserting an item at a given position Syntax: list.insert[index, item] E.g. &gt;&gt;&gt; l = [1, ["2", 4], 3.0] &gt;&gt;&gt; l.insert(0, 8.3) &gt;&gt;&gt; l [8.3, 1, ['2', 4], 3.0] Adding an item at the end of the listAdding an item at the end of the list Syntax: list.append[item] E.g. &gt;&gt;&gt; l.append(end) &gt;&gt;&gt; l [8.3, 1, ['2', 4], 3.0, end] </li> <li> Slide 11 &gt;&gt; l.sort() &gt;&gt;&gt; l ['a', 'b', 'c', 'd']"&gt; </li><li> 11 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Methods SortingSorting Syntax: list.sort() E.g. &gt;&gt;&gt; l = [1, 3, 2.0, 4] &gt;&gt;&gt; l.sort() &gt;&gt;&gt; l [1, 2.0, 3, 4] &gt;&gt;&gt; l=["c", "d", "a", "b"] &gt;&gt;&gt; l.sort() &gt;&gt;&gt; l ['a', 'b', 'c', 'd'] </li> <li> Slide 12 </li> <li> 12 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lists: Methods ReversingReversing Syntax: list.reverse() E.g. &gt;&gt;&gt; l = [1, 3, 2.0, 4] &gt;&gt;&gt; l.reverse() &gt;&gt;&gt; l [4, 2.0, 3, 1] </li> <li> Slide 13 </li> <li> 13 COMP 144 Programming Language Concepts Felix Hernandez-Campos Built-in Data Structures: Dictionaries A dictionary is an unordered collection of objects indexed by keysA dictionary is an unordered collection of objects indexed by keys Any object can be a keyAny object can be a key Any object can be a item indexed by a keyAny object can be a item indexed by a key Dictionaries are mutableDictionaries are mutable ExamplesExamples {} Empty dictionary {'item':'tire','price':20.99} Two-element dictionary </li> <li> Slide 14 &gt;&gt; str = 'item' &gt;&gt;&gt; d[str] 'tire'"&gt; </li><li> 14 COMP 144 Programming Language Concepts Felix Hernandez-Campos Dictionaries: Accessing items Syntax: list[key]Syntax: list[key] E.g. &gt;&gt;&gt; d = {'item':'tire','price':20.99} &gt;&gt;&gt; d[price'] 20.99 &gt;&gt;&gt; d[item] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? d[item] d[item] NameError: name 'item' is not defined &gt;&gt;&gt; str = 'item' &gt;&gt;&gt; d[str] 'tire' </li> <li> Slide 15 &gt;&gt; d =" title="15 COMP 144 Programming Language Concepts Felix Hernandez-Campos Dictionaries: Deleting items Syntax: del list[key]Syntax: del list[key] E.g. &gt;&gt;&gt; d ="&gt; </li><li> 15 COMP 144 Programming Language Concepts Felix Hernandez-Campos Dictionaries: Deleting items Syntax: del list[key]Syntax: del list[key] E.g. &gt;&gt;&gt; d = {'item':'tire','price':20.99} &gt;&gt;&gt; del d['item'] &gt;&gt;&gt; d {'price': 20.989999999999998} &gt;&gt;&gt; del d['brand'] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? del d['brand'] del d['brand'] KeyError: brand </li> <li> Slide 16 </li> <li> 16 COMP 144 Programming Language Concepts Felix Hernandez-Campos Dictionaries: Length Syntax: len(list)Syntax: len(list) E.g. &gt;&gt;&gt; d = {'item':'tire','price':20.99} &gt;&gt;&gt; len(d) 2 </li> <li> Slide 17 </li> <li> 17 COMP 144 Programming Language Concepts Felix Hernandez-Campos Dictionaries: Methods MembershipMembership Syntax: list.has_key(key) E.g. &gt;&gt;&gt; l = {'item':'tire','price':20.99} &gt;&gt;&gt; l.has_key('item') 1 &gt;&gt;&gt; l.has_key('brand') 0 </li> <li> Slide 18 </li> <li> 18 COMP 144 Programming Language Concepts Felix Hernandez-Campos Dictionaries: Methods List of keysList of keys Syntax: list.keys() E.g. &gt;&gt;&gt; l = {'item':'tire','price':20.99} &gt;&gt;&gt; l.keys() ['item', 'price'] List of valuesList of values Syntax: list.values() E.g. &gt;&gt;&gt; l.values() ['tire', 20.989999999999998] </li> <li> Slide 19 </li> <li> 19 COMP 144 Programming Language Concepts Felix Hernandez-Campos Built-in Data Structures: Tuples A tuple is an ordered collection of objectsA tuple is an ordered collection of objects Tuples can contain any type of objectTuples can contain any type of object Tuples are immutableTuples are immutable ExamplesExamples () Empty tuple 1, One-element tuple (!) (1, 2, 3.0) Three-element tuple 1, (2, 3.0) Nested tuple </li> <li> Slide 20 </li> <li> 20 COMP 144 Programming Language Concepts Felix Hernandez-Campos Built-in Data Structures: Tuples Commas are used to define tuplesCommas are used to define tuples Parentheses around tuples are optional E.g. &gt;&gt;&gt; 1,('2',2.0) (1, ('2', 2.0)) &gt;&gt;&gt; (1,('2',2.0)) (1, ('2', 2.0)) The one-element list requires a trailing comma &gt;&gt;&gt; 1, (1,) &gt;&gt;&gt; (1) This is not a tuple but a number 1 </li> <li> Slide 21 &gt;&gt; t = (1, 2," title="21 COMP 144 Programming Language Concepts Felix Hernandez-Campos Tuples: Accessing Items Syntax: tuple[index]Syntax: tuple[index] E.g. &gt;&gt;&gt; t = (1, 2,"&gt; </li><li> 21 COMP 144 Programming Language Concepts Felix Hernandez-Campos Tuples: Accessing Items Syntax: tuple[index]Syntax: tuple[index] E.g. &gt;&gt;&gt; t = (1, 2, (3, 4, 5)) &gt;&gt;&gt; t[1] 2 &gt;&gt;&gt; t[-1] (3, 4, 5) &gt;&gt;&gt; t[-1][1] 4 &gt;&gt;&gt; t[3] Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? t[3] t[3] IndexError: tuple index out of range </li> <li> Slide 22 &gt;&gt; len(t[2]) 3"&gt; </li><li> 22 COMP 144 Programming Language Concepts Felix Hernandez-Campos Tuples: No Deletion and Length No deletion!No deletion! Tuples are immutable Length:Length: Syntax: len(tuple) E.g. &gt;&gt;&gt; t = (1,2,(3,4,5)) &gt;&gt;&gt; len(t) 3 &gt;&gt;&gt; len(t[1]) Traceback (most recent call last): File " ", line 1, in ? File " ", line 1, in ? len(t[1]) len(t[1]) TypeError: len() of unsized object &gt;&gt;&gt; len(t[2]) 3 </li> <li> Slide 23 </li> <li> 23 COMP 144 Programming Language Concepts Felix Hernandez-Campos Tuples: Constructing Tuples ConcatenationConcatenation Syntax: tuple1 + tuple2 E.g. &gt;&gt;&gt; t = (1,2) + (3,) &gt;&gt;&gt; t (1, 2, 3) RepetitionRepetition Syntax: tuple * integer E.g. &gt;&gt;&gt; t * 5 (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3) </li> <li> Slide 24 </li> <li> 24 COMP 144 Programming Language Concepts Felix Hernandez-Campos Hierarchy of Numbers Source: Lutz &amp; Ascher, Learning Python, Figure 2-3 </li> <li> Slide 25 </li> <li> 25 COMP 144 Programming Language Concepts Felix Hernandez-Campos Hierarchy of Built-in Collections Source: Lutz &amp; Ascher, Learning Python, Figure 2-3 </li> <li> Slide 26 &gt;&gt; s1 'hello' &gt;&gt;&gt; n 4.0 &gt;&gt;&gt; m 3"&gt; </li><li> 26 COMP 144 Programming Language Concepts Felix Hernandez-Campos Statements: Assignment Syntax: reference = object or referenceSyntax: reference = object or reference E.g. &gt;&gt;&gt; a = 3 &gt;&gt;&gt; a 3 &gt;&gt;&gt; s1, n, m = "hello", 4.0, a &gt;&gt;&gt; s1 'hello' &gt;&gt;&gt; n 4.0 &gt;&gt;&gt; m 3 </li> <li> Slide 27 &gt;&gt; print 3.0e5 300000.0 &gt;&gt;&gt; name = "python" &gt;&gt;&gt; ver = 2.2 &gt;&gt;&gt; print "This is %(name)s %(ver).3f" % vars() This is python 2.200"&gt; </li><li> 27 COMP 144 Programming Language Concepts Felix Hernandez-Campos Statements: Print Syntax: print object or referenceSyntax: print object or reference E.g. &gt;&gt;&gt; print "hello", 'again' hello again &gt;&gt;&gt; print 3.0e5 300000.0 &gt;&gt;&gt; name = "python" &gt;&gt;&gt; ver = 2.2 &gt;&gt;&gt; print "This is %(name)s %(ver).3f" % vars() This is python 2.200 </li> <li> Slide 28 </li> <li> 28 COMP 144 Programming Language Concepts Felix Hernandez-Campos Selection Syntax:Syntax: if test: statements elif test: statements else: statements Conditional expressions:Conditional expressions: &gt;, =,, =, &gt;&gt; x = -3 &gt;&gt;&gt; if x &gt;&gt; if x &lt; 0: print "negative" elif x == 0: pri"&gt; </li> <li> 29 COMP 144 Programming Language Concepts Felix Hernandez-Campos Selection E.g.E.g. &gt;&gt;&gt; x = -3 &gt;&gt;&gt; if x &gt;&gt; if x &lt; 0: print "negative" elif x == 0: print "zero" else: print "positive" negative </li> <li> Slide 30 </li> <li> 30 COMP 144 Programming Language Concepts Felix Hernandez-Campos Sequence Iteration Syntax: for var in sequence:Syntax: for var in sequence:statements E.g. &gt;&gt;&gt; sum = 0 &gt;&gt;&gt; for i in range(1,10,2): sum = sum + i &gt;&gt;&gt; sum 25 Membership operator: inMembership operator: in </li> <li> Slide 31 </li> <li> 31 COMP 144 Programming Language Concepts Felix Hernandez-Campos Iteration Syntax: while test:Syntax: while test:statements E.g. &gt;&gt;&gt; sum = 0 &gt;&gt;&gt; i = 1 &gt;&gt;&gt; while i &gt;&gt; while i &lt; 10: sum = sum + i i = i + 2 &gt;&gt;&gt; sum 25 Break and continue are also possibleBreak and continue are also possible </li> <li> Slide 32 </li> <li> 32 COMP 144 Programming Language Concepts Felix Hernandez-Campos Functions Syntax:Syntax: def name(parameters): statements return object E.g. &gt;&gt;&gt; def incr(x): return x + 1 &gt;&gt;&gt; incr(3) 4 </li> <li> Slide 33 </li> <li> 33 COMP 144 Programming Language Concepts Felix Hernandez-Campos Functions Default valuesDefault values E.g. def ask_ok(prompt, retries=4, complaint='Yes or no!'): while 1: while 1: ok = raw_input(prompt) ok = raw_input(prompt) if ok in ('y', 'ye', 'yes'): return 1 if ok in ('y', 'ye', 'yes'): return 1 if ok in ('n', 'no', 'nop', 'nope'): if ok in ('n', 'no', 'nop', 'nope'): return 0 return 0 retries = retries - 1 retries = retries - 1 if retries &lt; 0: if retries &lt; 0: raise IOError, 'refusenik user' print complaint print complaint </li> <li> Slide 34 &gt;&gt; parrot(1000) &gt;&gt;&gt; parrot(action = 'VOOOOOM', voltage = 1000000) &gt;&gt;&gt; parrot('a thousand', state = 'pushing up the daisies') &gt;&gt;&gt; parrot('a million', 'bereft of life', 'jump')"&gt; </li><li> 34 COMP 144 Programming Language Concepts Felix Hernandez-Campos Functions Parameter passing by position and by nameParameter passing by position and by name E.g. def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): print "-- This parrot wouldn't", action, print "-- This parrot wouldn't", action, print "if you put", voltage, "Volts through it." print "if you put", voltage, "Volts through it." print "-- Lovely plumage, the", type print "-- Lovely plumage, the", type print "-- It's", state, "!" print "-- It's", state, "!" &gt;&gt;&gt; parrot(1000) &gt;&gt;&gt; parrot(action = 'VOOOOOM', voltage = 1000000) &gt;&gt;&gt; parrot('a thousand', state = 'pushing up the daisies') &gt;&gt;&gt; parrot('a million', 'bereft of life', 'jump') </li> <li> Slide 35 </li> <li> 35 COMP 144 Programming Language Concepts Felix Hernandez-Campos Functions Functions can also have an arbitrary number of parametersFunctions can also have an arbitrary number of parameters Passed as a dictionary or as list of remaining parameters See documentation We will talk about lambda forms and other functional programming techniquesWe will talk about lambda forms and other functional programming techniques After the Haskell lectures </li> <li> Slide 36 </li> <li> 36 COMP 144 Programming Language Concepts Felix Hernandez-Campos Reading Assignment Guido van Rossum and Fred L. Drake, Jr. (ed.), Python tutorial, PythonLabs, 2001.Guido van Rossum and Fred L. Drake, Jr. (ed.), Python tutorial, PythonLabs, 2001. Read chapters 3 to 5 http://www.python.org/doc/current/tut/tut.html http://www.python.org/doc/current/tut/tut.html Write some simple programs Eric S. Raymond, Why Python?Eric S. Raymond, Why Python? http://www.linuxjournal.com/article.php?sid=3882 http://www.linuxjournal.com/article.php?sid=3882 </li> </ul>