530 likes | 717 Views
Python - 2. Jim Eng jimeng@umich.edu. Overview. Lists Dictionaries Try ... except Methods and Functions Classes and Objects Midterm Review. Patterns in programming - 1. Sequential steps Conditional steps Repeated steps Stored and reused steps. Patterns in programming - 2. Input
E N D
Python - 2 • Jim Eng • jimeng@umich.edu
Overview • Lists • Dictionaries • Try ... except • Methods and Functions • Classes and Objects • Midterm Review
Patterns in programming - 1 • Sequential steps • Conditional steps • Repeated steps • Stored and reused steps
Patterns in programming - 2 • Input • Processing • Output
>>> pals = list() >>> pals.append("Glenn") >>> pals.append("Sally") >>> pals.append("Joe") >>> print pals ['Glenn', 'Sally', 'Joe'] >>> >>> print pals[1] Sally >>>
>>> print pals ['Glenn', 'Sally', 'Joe'] >>> pals[2] = 'Joseph' >>> print pals ['Glenn', 'Sally', 'Joseph'] >>>
>>> num = 1 >>> for pal in pals: ... print num, ") ", pal ... num = num + 1 ... 1 ) Glenn 2 ) Sally 3 ) Joseph >>> print num 4 >>>
>>> pals.sort()>>> num = 1>>> for pal in pals:... print num, ") ", pal... num = num + 1... 1 ) Glenn2 ) Joseph3 ) Sally>>>
>>> def print_list(list):... num = 1... for item in list:... print num, ") ", item... num = num + 1... >>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally>>>
>>> pals.append('Erin')>>> pals.append('Michele') >>> pals.insert(3,'Aaron')>>>>>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally4 ) Aaron5 ) Erin6 ) Michele>>>
>>> nums = list()>>> nums.append(12345)>>> nums.append(15000)>>> nums.append(13000)>>> nums.append(12000) >>>>>> print_list(nums)1 ) 123452 ) 150003 ) 130004 ) 12000>>>
>>> nums.append(12)>>> print nums[12345, 15000, 13000, 12000, 12]>>> nums.sort()>>> print_list(nums)1 ) 122 ) 120003 ) 123454 ) 130005 ) 15000>>>
>>> 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... >>>
>>> 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... >>>
>>> 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>>>
>>> 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']>>>
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
>>> 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'}>>>
>>> print pal['phone']734-555-1234 >>>>>> print pal['age']Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'age'>>>
>>> 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>>>
>>> for key in pal :... print key... phonelastemailfirst>>>
>>> for key in pal :... print key, ": ", pal[key]... phone : 734-555-1234last : Silverioemail : gsilver@example.orgfirst : Gonzalo>>>
>>> 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']>>>
>>> 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>>>
>>> dir(pal)[..., 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']>>>
>>> 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')]>>>
>>> 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)>>>
>>> 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'}]>>>
>>> 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 ---- >>>
>>> 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 "<stdin>", line 3, in <module>KeyError: 'age'>>>
>>> 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 "<stdin>", line 3, in <module>KeyError: 'age'>>>
>>> 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 ---- >>>
>>> 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'}>>>
>>> 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'}]>>>
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 ...
fahrenheit = input("Enter F: ") celsius = convert(fahrenheit) print "C: ", celsius % python conv1.py Enter F: Fred Traceback (most recent call last): File "conv1.py", line 1, in <module> ftemp = input("Enter F:"); File "<string>", line 1, in <module> NameError: name 'Fred' is not defined
>>> print int('42')42 >>>>>> print int(42.5)42 >>>>>> print int('forty-two')Traceback (most recent call last): File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: 'forty-two'>>>
>>> try:... print int('42')... except:... print 'oops'... 42 >>> try:... print int('forty-two')... except:... print 'oops'... oops
>>> def safeint(val):... try:... print int(val)... except:... print 'oops'... >>> safeint(42)42>>> safeint(42.5)42>>> safeint('42')42>>> safeint('forty-two')oops>>>
f = input("Enter the temperature in farenheit: ") c = convert(f) print "The temperature in celsius is ", c $ python conv1.py Enter the temperature in farenheit: FredTraceback (most recent call last): File "f2c.py", line 6, in <module> f = input("Enter the temperature in farenheit: ") File "<string>", line 1, in <module>NameError: name 'Fred' is not defined
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'
$ 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$
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
>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc')<type 'str'>>>>
>>> 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']>>>
>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc')<type 'str'>>>>
>>> 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']>>>
>>> print len(pals)6>>> print type(pals)<type 'list'>>>> print pals.count('b')1>>> print pals.index('b')2>>>
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
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)