COE808 Lecture Notes Tuesday Feb 23, 2010

Topics

Python

 

While loop, dynamic typing, % formatting operator

principal=1000

rate = 0.05

numYears = 5

year = 1

while year <= numYears:

    principal = principal * (1 + rate) #"type" changes

    #print year, principal

    print "%3d %0.2f" % (year, principal)

    year += 1sym = next input token

 

 

If statements

s = 'coe808'

if 'coe' in s: #in operator

    print "yes"

else:

    print "no"

x = 'coe' in s #Boolean data type

print x

print "coe course? " + str(x)

if '618' in s:

    pass

else:

    print "No"

if not '618' in s:

    print "no"

a = True

b = False

if a and not b:

    print "aNotb"

else:

    print "NOT aNotb"

 

 

Strings

 

 

a = "Hello world"

b = 'hi'

c = """Content-type: text/html

<h1> Hello world</h1>

<a href = "./foo.html">here</a>"""

print a + "\n" + b + "\n"+ c

print a[0]

print a[:5]

print a[6:]

print a[2:7]

print a[1:-1]

#Conversions

x = "123"

y = "4"

z = x + y

print z

z = int(x) + int(y)

print z

x =56

print "x is %d" % x

Lists

 

names = ["Alice", "Bob", "Chloe"]

print names[1]

names.append("Dave")

print names

names.append("Frank")

print names

names.insert(3, "Eve")

print names

names [0:1] = ["ALICE", "BOB"]

print names

#Concatenate lists

a = [ 1, 2, 3]

b = [4, 5]

c = a + b

print c

#list elements can be any type including other lists

d=[1, "Dave", [5, 6, ["hi", "bye"]], 3.14,10]

print d[1]

print d[2][1]

print d[2][2][0]

 

 

Tuples

person = ("Alice", "Jones", 555)

print person[1]

first, last, num = person

print "First name: " + first +"\n" + "Number: " + str(num)

 

filename = "stocks.csv"

portfolio = []

for line in open(filename):

    fields = line.split(",")

    name = fields[0]

    shares = int(fields[1])

    price = float(fields[2])

    stock = (name, shares, price)

    portfolio.append(stock)

 

#eg portfolio[0] could be ('GOOG', 100, 560.25)

total = 0.0

for name, shares, price in portfolio:

    total += shares * price

 

 

Sets

 

s = set([1, 2, 3])

t = set([1, 1, 1])

h = set("Hello")

print s

print t

print h

a = set([1,2,3])

b = set([3, 4, 5])

union = a | b

print union

intersection = a & b

print intersection

diff = a - b

print "a-b", diff

symmetricDiff = a ^ b

print "a ^ b", symmetricDiff

 

 

Dictionaries

#dictionary is an associative array (i.e. hash table)

student = {

    "name" : "Alice",

    "test" : 75.0,

    "lab"  : 10.0

    }

print student

print student["name"]

print student["test"] + student["lab"]

student["lab"] += 5

print student["test"] + student["lab"]

 

if "name" in student:

    print "hi", student["name"]

silly = {"x" : 1,

         "x" : 2}

print silly

students = {

    "Alice" : [1, 2],

    "Bob" : [3, 4]

    }

if "Bob" in students:

    print students["Bob"][1]

 

For Loops

 

for i in [1, 2, 3]:

    print i, "squared:", i*i

#using range(a,b)

for i in range(1,5):

    print i, "cubed:", i*i*i

 

#using range(a,b,c)

for i in range(1,7,2):

    print i, "doubled:", (i+i)

for i in range(10, 0, -3):

    print i, "tripled:", 3*i

 

#Iterating with strings, lists, dicts, files

a = "hi"

for i in a:

    print i

b = ["foo", "bar"]

for i in b:

    print i

c = {"Alice": 5, "Bob" : 6}

for i in c:

    print i, c[i]

f = open("LoopsDemo.py")

for i in f:

    print i

 

 

 

Functions

def remainder(a, b):

    q = a // b #integer division

    r = a - q*b

    return r

 

#reurn multiple values as a tuple

def divide(a, b):

    q = a //b

    r = a - q*b

    return (q, r)

 

#default arg values

def incr(a, i=1):

    return a+i

 

print remainder(11,3)

q, rem = divide(11,3)

print q, rem

print incr(5)

print incr(5, 2)

 

Generators

 

def countdown(n):

    while n >= 0:

        yield n  #Generate a value

        n -= 1

 

c = countdown(3)

print c.next()

print c.next()

 

for i in countdown(4):

    print i    

 

 

Coroutines

 

def printMatches(lookFor):

    while True:

        line = (yield)

        if lookFor in line:

            print line

 

matcher = printMatches("coe808")

matcher.next()  #Advance to first (yield)

matcher.send("is this the room for coe808?")

matcher.send("foo bar")

matcher.send("foo coe808 bar")

 

 

Classes and objects

Everything in python is an object.  (Interactive demo)

class Stack(object): #inherit from object

    """

    A stack

    """

    def __init__(self):

        self.stack = []

    def push(self, object):

        self.stack.append(object)

    def pop(self):

        return self.stack.pop()

    def length(self):

        return len(self.stack)

 

s = Stack()

s.push(5)

s.push([1,2,"bye"])

s.push("hi")

print s

print s.pop()

print s.pop()

print s.__doc__

 

#re-write inherit from list

class Stack(list):

    def push(self, object):

        self.append(object)

 

s = Stack()

s.push("abc")

s.push("def")

print s.pop()