Post on 25-Dec-2015
Python, Part 2
Python Object Equality
x == yx is y
In Java:(x.equals(y))(x == y)
Python Exceptions
try: do_stuff() if something_bad_has_happened(): raise MyException, "something happened" except MyException, e: print "My exception occurred, value: ", e.value
Python Exceptions
while True: try: x = int(raw_input("Please enter a number: ")) except ValueError: print "That was no valid number. Try again."
Functional programming features: map
lst = ["1", "2", "3", "4", "5"] nums = map(string.atoi, lst) # nums is now [1, 2, 3, 4, 5]
map
def add(x, y): return x + y
lst1 = [1, 2, 3, 4, 5] lst2 = [6, 7, 8, 9, 10]
lst_sum = map(add, lst1, lst2) # lst_sum == [7, 9, 11, 13, 15]
reduce
def add(x, y): return x + y
lst1 = [1, 2, 3, 4, 5] sum = reduce(add, lst1) # sum == 15
filter
nums = range(0,101) # [0, 1, ... 100] def is_odd(x): return x % 2 == 1
odd_nums = filter(is_odd, nums) # odd_nums == [1, 3, 5, ... 99]
Lambda: Anonymous functions
t = lambda x,y: x*y
def t: return x*y
answer = t(2,3)
LambdaUseful for map, reduce, filter:
nums = range(0,101) # [0, 1, ... 100]
odd_nums = filter(lambda x: x%2==1, nums) # odd_nums == [1, 3, 5, ... 99]
Pass Comparators to Sort:
#return data which has groups of a name followed by 2 scores.def get_data(): return [('fred',10,1),('bill',3,0),('betty',5,8)]
a=get_data()
a.sort(lambda x, y: cmp(x[2],y[2])) print a
>>>[('bill', 3, 0), ('fred', 10, 1), ('betty', 5, 8)]
Each “file” is a module.
Consider module called “hello.py”:
def printer(message): print message
In module main.py write:import hellohello.printer(“hello”)
-OR- from hello import printerprinter(“hello”)
from hello import *
Main Module
What about interactive session? Is it a module??
Yes: __main__
Modules executed on import. In many modules you will see:
if __name__ == "__main__": main()
Python Classes:
Attributes can be added/deleted dynamically (no declaring)
Keyword self (like this) passed into all class methods
Special methods __init__ (Constructor)__del__ (Destructor)
class Student: def __init__(self, name, hours, qpts): self.name = name self.hours = hours self.qpts = qpts
def getName(self): return self.name
def gpa(self): return self.qpts/self.hours
from student import *
aStudent = Student(“Mary Adams”, 127, 228)gpa = aStudent.gpa()print gpa
s = Student(…) calls the constructor. To call the destructor:s = 0
Creating a list the old way…
>>> squares = [] >>> for x in range(10): squares.append(x**2) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
List Comprehensions
>>> squares = [] >>> for x in range(10):
squares.append(x**2) >>> squares [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>>squares = [x**2 for x in range(10)]
List Comprehensions
>>> vec = [-4, -2, 0, 2, 4] >>> [x*2 for x in vec]
List Comprehensions
>>> vec = [-4, -2, 0, 2, 4] >>> [x*2 for x in vec] [-8, -4, 0, 4, 8]
>>> vec = [-4, -2, 0, 2, 4] >>> [x for x in vec if x >= 0]
>>> vec = [-4, -2, 0, 2, 4] >>> [x for x in vec if x >= 0] [0, 2, 4]
Can do embedded loops too
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Can do embedded loops too
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]