Download presentation
Presentation is loading. Please wait.
Published byEmory Beasley Modified over 9 years ago
1
Python - 2 Jim Eng jimeng@umich.edu
2
Overview Lists Dictionaries Try... except Methods and Functions Classes and Objects Midterm Review
3
Patterns in programming - 1 Sequential steps Conditional steps Repeated steps Stored and reused steps
4
Patterns in programming - 2 Input Processing Output
5
>>> pals = list() >>> pals.append("Glenn") >>> pals.append("Sally") >>> pals.append("Joe") >>> print pals ['Glenn', 'Sally', 'Joe'] >>> >>> print pals[1] Sally >>>
6
>>> print pals ['Glenn', 'Sally', 'Joe'] >>> pals[2] = 'Joseph' >>> print pals ['Glenn', 'Sally', 'Joseph'] >>>
7
>>> num = 1 >>> for pal in pals:... print num, ") ", pal... num = num + 1... 1 ) Glenn 2 ) Sally 3 ) Joseph >>> print num 4 >>>
8
>>> pals.sort()>>> num = 1>>> for pal in pals:... print num, ") ", pal... num = num + 1... 1 ) Glenn2 ) Joseph3 ) Sally>>>
9
>>> def print_list(list):... num = 1... for item in list:... print num, ") ", item... num = num + 1... >>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally>>>
10
>>> pals.append('Erin')>>> pals.append('Michele') >>> pals.insert(3,'Aaron')>>>>>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally4 ) Aaron5 ) Erin6 ) Michele>>>
11
>>> nums = list()>>> nums.append(12345)>>> nums.append(15000)>>> nums.append(13000)>>> nums.append(12000) >>>>>> print_list(nums)1 ) 123452 ) 150003 ) 130004 ) 12000>>>
12
>>> nums.append(12)>>> print nums[12345, 15000, 13000, 12000, 12]>>> nums.sort()>>> print_list(nums)1 ) 122 ) 120003 ) 123454 ) 130005 ) 15000>>>
13
>>> def foot_label(num):... label = "feet"... if(num == 1):... label = "foot"... return label... >>> def inch_label(num):... label = "inches"... if(num == 1):... label = "inch"... return label... >>>
14
>>> def print_feet(inches_in):... feet = inches_in / 12... inches = inches_in % 12... msg = str(inches_in)... msg = msg + " inches equals " + str(feet)... msg = msg + " " + foot_label(feet)... if(inches > 0):... msg = msg + " and " + str(inches)... msg = msg + " " + inch_label(inches)... print msg... >>>
15
>>> print_feet(12000)12000 inches equals 1000 feet>>> print_feet(nums[1])12000 inches equals 1000 feet >>> for num in nums:... print_feet(num)... 12 inches equals 1 foot12000 inches equals 1000 feet12345 inches equals 1028 feet and 9 inches13000 inches equals 1083 feet and 4 inches15000 inches equals 1250 feet>>>
16
>>> list2 = list()>>> list2.append("Jennifer")>>> list2.append("Jack")>>> list2['Jennifer', 'Jack']>>> print list2['Jennifer', 'Jack']>>> print pals['Glenn', 'Joseph', 'Sally', 'Aaron', 'Erin', 'Michele']>>> new_list = pals + list2>>> print new_list['Glenn', 'Joseph', 'Sally', 'Aaron', 'Erin', 'Michele', 'Jennifer', 'Jack']>>>
17
Lists are OK We can use them to keep things in order We can add things to lists -- pals.append('Joe'), pals.insert(3,'Aaron') We can sort them -- pals.sort() We can directly access individual items -- pals[2] We can iterate through the items -- for pal in pals: We can concatenate lists -- list3 = list1 + list2
18
>>> pal = dict() >>>>>> pal['first'] = 'Gonzalo'>>> pal['last'] = 'Silverio'>>> pal['email'] = 'gsilver@example.org'>>> pal['phone'] = '734-555- 1234' >>>>>> print pal{'phone': '734-555-1234', 'last': 'Silverio', 'email': 'gsilver@example.org', 'first': 'Gonzalo'}>>>
19
>>> print pal['phone']734-555-1234 >>>>>> print pal['age']Traceback (most recent call last): File " ", line 1, in KeyError: 'age'>>>
20
>>> print pal.get('age', 'Age not available')Age not available >>>>>> print pal.get('phone', 'Phone not available')734-555-1234>>> >>> print pal.get('age', 21)21>>>
21
>>> for key in pal :... print key... phonelastemailfirst>>>
22
>>> for key in pal :... print key, ": ", pal[key]... phone : 734-555-1234last : Silverioemail : gsilver@example.orgfirst : Gonzalo>>>
23
>>> dir(pal)['__class__', '__cmp__', '__contains__', '__delattr__', '__delitem__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__str__', 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']>>>
24
>>> dir('Hello')[..., 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']>>> print 'Hello'.upper()HELLO>>> print 'Hello'.swapcase()hELLO>>> print 'lord of the rings'.title()Lord Of The Rings>>>
25
>>> dir(pal)[..., 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']>>>
26
>>> pal.keys()['phone', 'last', 'email', 'first']>>> pal.values()['734-555-1234', 'Silverio', 'gsilver@example.org', 'Gonzalo']>>> pal.has_key('phone')True>>> pal.has_key('age')False>>> pal.items()[('phone', '734-555-1234'), ('last', 'Silverio'), ('email', 'gsilver@example.org'), ('first', 'Gonzalo')]>>>
27
>>> pals = list()>>> pal = dict()>>> pal['first'] = 'Gonzalo'>>> pal['last'] = 'Silverio'>>> pal['email'] = 'gsilver@example.org'>>> pal['phone'] = '734-555- 1234'>>> print pal{'phone': '734-555-1234', 'last': 'Silverio', 'email': 'gsilver@example.org', 'first': 'Gonzalo'}>>> pals.append(pal)>>>
28
>>> pal = dict()>>> print pal{}>>> pal['first'] = 'Jim'>>> pal['last'] = 'Eng'>>> pal['email'] = 'jimeng@umich.edu'>>> pal['phone'] = '734-555-4123'>>> pals.append(pal)>>> print pals[{'phone': '734-555- 1234', 'last': 'Silverio', 'email': 'gsilver@example.org', 'first': 'Gonzalo'}, {'phone': '734-555-4123', 'last': 'Eng', 'email': 'jimeng@umich.edu', 'first': 'Jim'}]>>>
29
>>> for pal in pals:... for key in pal:... print key, ": ", pal[key]... print " ---- "... phone : 734-555-1234last : Silverioemail : gsilver@example.orgfirst : Gonzalo ---- phone : 734-555-4123last : Engemail : jimeng@umich.edufirst : Jim ---- >>>
30
>>> for pal in pals:... for key in keys:... print key, ": ", pal[key]... print " ---- "... first : Gonzalolast : Silveriophone : 734-555- 1234email : gsilver@example.orgage : Traceback (most recent call last): File " ", line 3, in KeyError: 'age'>>>
32
>>> nk = " not known" >>> for pal in pals:... for key in keys:... print key, ": ", pal.get(key, key + nk)... print " ---- "... first : Gonzalolast : Silveriophone : 734- 555-1234email : gsilver@example.orgage : age not knownbirthday : birthday not known ---- first : Jimlast : Engphone : 734-555-4123email : jimeng@umich.eduage : age not knownbirthday : birthday not known ---- >>>
33
>>> person = dict()>>> for key in keys:... val = raw_input(key + ": ")... person[key] = val... first: Denzellast: Washingtonphone: 323-555-6789email: denzel@celeb.orgage: 54birthday: Dec 28>>> print person{'last': 'Washington', 'age': '54', 'phone': "323-555-6789", 'birthday': 'Dec 28', 'email': 'denzel@celeb.org', 'first': 'Denzel'}>>>
34
>>> pals.append(person)>>> pals[{'phone': '734-555- 1234', 'last': 'Silverio', 'email': 'gsilver@example.org', 'first': 'Gonzalo'}, {'phone': '734-555-4123', 'last': 'Eng', 'email': 'jimeng@umich.edu', 'first': 'Jim'}, {'last': 'Washington', 'age': '54', 'phone': "323-555-6789", 'birthday': 'Dec 28', 'email': 'denzel@celeb.org', 'first': 'Denzel'}]>>>
35
Dictionaries are OK We can use a dictionary to associate keys and values We can describe an individual by its attributes We can iterate over the keys and access the values And so much more...
36
% python conv1.py Enter F: Fred Traceback (most recent call last): File "conv1.py", line 1, in ftemp = input("Enter F:"); File " ", line 1, in NameError: name 'Fred' is not defined fahrenheit = input("Enter F: ") celsius = convert(fahrenheit) print "C: ", celsius
37
>>> print int('42')42 >>>>>> print int(42.5)42 >>>>>> print int('forty-two')Traceback (most recent call last): File " ", line 1, in ValueError: invalid literal for int() with base 10: 'forty- two'>>>
38
>>> try:... print int('42')... except:... print 'oops'... 42 >>> try:... print int('forty-two')... except:... print 'oops'... oops
39
>>> def safeint(val):... try:... print int(val)... except:... print 'oops'... >>> safeint(42)42>>> safeint(42.5)42>>> safeint('42')42>>> safeint('forty-two')oops>>>
40
$ python conv1.py Enter the temperature in farenheit: FredTraceback (most recent call last): File "f2c.py", line 6, in f = input("Enter the temperature in farenheit: ") File " ", line 1, in NameError: name 'Fred' is not defined f = input("Enter the temperature in farenheit: ") c = convert(f) print "The temperature in celsius is ", c
41
try:f = input("Enter the temperature in farenheit: ")c = convert(f)print "The temperature in celsius is ",cexcept:print 'Please enter a temperature in farenheit'
42
$ python conv1.py Enter the temperature in farenheit: 212The temperature in celsius is 100 $$ python conv1.py Enter the temperature in farenheit: FredPlease enter a temperature in farenheit$ $ python conv1.py Enter the temperature in farenheit: 42.5The temperature in celsius is 5.83333333333$
43
Try... except We can "try" to execute parts of a program where errors might cause the program to crash We can "catch" errors and handle them gracefully
44
>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc') >>>
45
>>> dir('abc')['capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']>>>
46
>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc') >>>
47
>>> pals = list()>>> pals.append('a')>>> pals.append('x')>>> pals.append('b')>>> pals.append('y')>>> pals.append('c')>>> pals.append('z')>>> print pals['a', 'x', 'b', 'y', 'c', 'z']>>> dir(pals)['append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']>>>
48
>>> print len(pals)6>>> print type(pals) >>> print pals.count('b')1>>> print pals.index('b')2>>>
49
class Simple(): num = 0 def incr(self): self.num = self.num + 1 return self.num def square(self): self.num = self.num * self.num return self.num def decr(self): self.num = self.num - 1 return self.num
50
x = Simple()print dir(x)print "x.num == ", x.numprint "x.incr()",x.incr()print "x.incr()",x.incr)print "x.decr()",x.dec()print "x.incr()",x.incr()print "x.square()",x.square()print "x.decr()",x.decr()print type(x)
51
$ python simple.py ['__doc__', '__module__', 'decr', 'incr', 'num', 'square']x.num == 0x.incr() 1x.incr() 2x.decr() 1x.incr() 2x.square() 4x.decr() 3
52
Classes and Objects We can define classes and then create instances of our classes A class encapsulates data and methods related to a particular type of object An instance of a class is an object We invoke methods on objects Sometimes we pass an object as a parameter to a function
53
Overview Lists Dictionaries Try... except Methods and Functions Classes and Objects Midterm Review
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.