python - 2

53
Python - 2 Jim Eng [email protected]

Upload: kalli

Post on 14-Jan-2016

52 views

Category:

Documents


0 download

DESCRIPTION

Python - 2. Jim Eng [email protected]. 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 - PowerPoint PPT Presentation

TRANSCRIPT

Page 2: Python - 2

Overview

•Lists

•Dictionaries

•Try ... except

•Methods and Functions

•Classes and Objects

•Midterm Review

Page 3: Python - 2

Patterns in programming - 1

•Sequential steps

•Conditional steps

•Repeated steps

•Stored and reused steps

Page 4: Python - 2

Patterns in programming - 2

•Input

•Processing

•Output

Page 5: Python - 2

>>> pals = list() >>> pals.append("Glenn") >>> pals.append("Sally") >>> pals.append("Joe") >>> print pals ['Glenn', 'Sally', 'Joe'] >>>>>> print pals[1]Sally>>>

Page 6: Python - 2

>>> print pals ['Glenn', 'Sally', 'Joe'] >>> pals[2] = 'Joseph'>>> print pals ['Glenn', 'Sally', 'Joseph'] >>>

Page 7: Python - 2

>>> num = 1>>> for pal in pals: ... print num, ") ", pal ... num = num + 1 ... 1 ) Glenn 2 ) Sally 3 ) Joseph >>> print num4>>>

Page 8: Python - 2

>>> pals.sort()>>> num = 1>>> for pal in pals:... print num, ") ", pal... num = num + 1... 1 ) Glenn2 ) Joseph3 ) Sally>>>

Page 9: Python - 2

>>> def print_list(list):... num = 1... for item in list:... print num, ") ", item... num = num + 1... >>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally>>>

Page 10: Python - 2

>>> pals.append('Erin')>>> pals.append('Michele')>>> pals.insert(3,'Aaron')>>>>>> print_list(pals)1 ) Glenn2 ) Joseph3 ) Sally4 ) Aaron5 ) Erin6 ) Michele>>>

Page 11: Python - 2

>>> nums = list()>>> nums.append(12345)>>> nums.append(15000)>>> nums.append(13000)>>> nums.append(12000)>>>>>> print_list(nums)1 ) 123452 ) 150003 ) 130004 ) 12000>>>

Page 12: Python - 2

>>> nums.append(12)>>> print nums[12345, 15000, 13000, 12000, 12]>>> nums.sort()>>> print_list(nums)1 ) 122 ) 120003 ) 123454 ) 130005 ) 15000>>>

Page 13: Python - 2

>>> 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... >>>

Page 14: Python - 2

>>> 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... >>>

Page 15: Python - 2

>>> 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>>>

Page 16: Python - 2

>>> 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']>>>

Page 17: Python - 2

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

Page 18: Python - 2

>>> pal = dict()>>>>>> pal['first'] = 'Gonzalo'>>> pal['last'] = 'Silverio'>>> pal['email'] = '[email protected]'>>> pal['phone'] = '734-555-1234'>>>>>> print pal{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}>>>

Page 19: Python - 2

>>> print pal['phone']734-555-1234>>>>>> print pal['age']Traceback (most recent call last): File "<stdin>", line 1, in <module>KeyError: 'age'>>>

Page 20: Python - 2

>>> 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>>>

Page 21: Python - 2

>>> for key in pal :... print key... phonelastemailfirst>>>

Page 22: Python - 2

>>> for key in pal :... print key, ": ", pal[key]... phone : 734-555-1234last : Silverioemail : [email protected] : Gonzalo>>>

Page 23: Python - 2

>>> 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']>>>

Page 24: Python - 2

>>> 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>>>

Page 25: Python - 2

>>> dir(pal)[..., 'clear', 'copy', 'fromkeys', 'get', 'has_key', 'items', 'iteritems', 'iterkeys', 'itervalues', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']>>>

Page 26: Python - 2

>>> pal.keys()['phone', 'last', 'email', 'first']>>> pal.values()['734-555-1234', 'Silverio', '[email protected]', 'Gonzalo']>>> pal.has_key('phone')True>>> pal.has_key('age')False>>> pal.items()[('phone', '734-555-1234'), ('last', 'Silverio'), ('email', '[email protected]'), ('first', 'Gonzalo')]>>>

Page 27: Python - 2

>>> pals = list()>>> pal = dict()>>> pal['first'] = 'Gonzalo'>>> pal['last'] = 'Silverio'>>> pal['email'] = '[email protected]'>>> pal['phone'] = '734-555-1234'>>> print pal{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}>>> pals.append(pal)>>>

Page 28: Python - 2

>>> pal = dict()>>> print pal{}>>> pal['first'] = 'Jim'>>> pal['last'] = 'Eng'>>> pal['email'] = '[email protected]'>>> pal['phone'] = '734-555-4123'>>> pals.append(pal)>>> print pals[{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}, {'phone': '734-555-4123', 'last': 'Eng', 'email': '[email protected]', 'first': 'Jim'}]>>>

Page 29: Python - 2

>>> for pal in pals:... for key in pal:... print key, ": ", pal[key]... print " ---- "... phone : 734-555-1234last : Silverioemail : [email protected] : Gonzalo ---- phone : 734-555-4123last : Engemail : [email protected] : Jim ---- >>>

Page 30: Python - 2

>>> for pal in pals:... for key in keys:... print key, ": ", pal[key]... print " ---- "... first : Gonzalolast : Silveriophone : 734-555-1234email : [email protected] : Traceback (most recent call last): File "<stdin>", line 3, in <module>KeyError: 'age'>>>

Page 31: Python - 2

>>> for pal in pals:... for key in keys:... print key, ": ", pal[key]... print " ---- "... first : Gonzalolast : Silveriophone : 734-555-1234email : [email protected] : Traceback (most recent call last): File "<stdin>", line 3, in <module>KeyError: 'age'>>>

Page 32: Python - 2

>>> 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 : [email protected] : age not knownbirthday : birthday not known ---- first : Jimlast : Engphone : 734-555-4123email : [email protected] : age not knownbirthday : birthday not known ---- >>>

Page 33: Python - 2

>>> person = dict()>>> for key in keys:... val = raw_input(key + ": ")... person[key] = val... first: Denzellast: Washingtonphone: 323-555-6789email: [email protected]: 54birthday: Dec 28>>> print person{'last': 'Washington', 'age': '54', 'phone': "323-555-6789", 'birthday': 'Dec 28', 'email': '[email protected]', 'first': 'Denzel'}>>>

Page 34: Python - 2

>>> pals.append(person)>>> pals[{'phone': '734-555-1234', 'last': 'Silverio', 'email': '[email protected]', 'first': 'Gonzalo'}, {'phone': '734-555-4123', 'last': 'Eng', 'email': '[email protected]', 'first': 'Jim'}, {'last': 'Washington', 'age': '54', 'phone': "323-555-6789", 'birthday': 'Dec 28', 'email': '[email protected]', 'first': 'Denzel'}]>>>

Page 35: Python - 2

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 ...

Page 36: Python - 2

% 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

fahrenheit = input("Enter F: ")celsius = convert(fahrenheit)print "C: ", celsius

Page 37: Python - 2

>>> 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'>>>

Page 38: Python - 2

>>> try:... print int('42')... except:... print 'oops'... 42>>> try:... print int('forty-two')... except:... print 'oops'... oops

Page 39: Python - 2

>>> def safeint(val):... try:... print int(val)... except:... print 'oops'... >>> safeint(42)42>>> safeint(42.5)42>>> safeint('42')42>>> safeint('forty-two')oops>>>

Page 40: Python - 2

$ 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

f = input("Enter the temperature in farenheit: ")c = convert(f)print "The temperature in celsius is ", c

Page 41: Python - 2

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'

Page 42: Python - 2

$ 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$

Page 43: Python - 2

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

Page 44: Python - 2

>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc')<type 'str'>>>>

Page 45: Python - 2

>>> 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']>>>

Page 46: Python - 2

>>> print len('abc')3>>> print 'abc'.upper()ABC>>> print 'abc'.isupper()False>>> print type('abc')<type 'str'>>>>

Page 47: Python - 2

>>> 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']>>>

Page 48: Python - 2

>>> print len(pals)6>>> print type(pals)<type 'list'>>>> print pals.count('b')1>>> print pals.index('b')2>>>

Page 49: Python - 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

Page 50: Python - 2

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)

Page 51: Python - 2

$ python simple.py ['__doc__', '__module__', 'decr', 'incr', 'num', 'square']x.num == 0x.incr() 1x.incr() 2x.decr() 1x.incr() 2x.square() 4x.decr() 3<type 'instance'>

Page 52: Python - 2

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

Page 53: Python - 2

Overview

•Lists

•Dictionaries

•Try ... except

•Methods and Functions

•Classes and Objects

•Midterm Review