 
   
   
   
   
   
   
   
   
   
   
CS256
Chris Pollett
Sep 18, 2017
a = "Hello" b = 'Good "bye"' c = """ Triple quotes one can go over multiple lines """ d = ''' this one works as well '''
a = "Hello World" b = a[4] # b is 'o' c = a[:5] # c is 'Hello' d = a[6:] # d is 'World' e = a[3:8] # e is "lo Wo"
my_list = ['YO', 1.2, 7, "HI", ["scary nested list", "watch out!"]] my_empty_list = [] # or list()
b = my_list[0] # b is now: 'YO' c = my_list[4][1] # c is now: 'watch out!' d = my_list[1:3] # d is [1.2, 7] e = my_list[2:] # e is [7, 'HI', ['scary nested list', 'watch out!']]
my_list.append("an end") #my_list now 
    #['YO', 1.2, 7, 'HI', ['scary nested list', 'watch out!'], 'an end']
my_list.insert(2, 3) # my_list now
    #['YO', 1.2, 3, 7, 'HI', ['scary nested list', 'watch out!'], 'an end']
a = [1, 2, 3] + [4, 5] #a is [1, 2, 3, 4, 5]
import sys if(len(sys.argv)) != 2: #notice sys.argv is a list of command-line args and we found its length print "Please supply a filename" raise SystemExit(1) # throw an error and exit f = open(sys.argv[1]) #program name is argv[0] lines = f.readlines() # reads all lines into list one go f.close() #convert inputs to list of ints ivalues = [int(line) for line in lines] # print min and max print "The min is ", min(ivalues) print "The max is", max(ivalues)
import glob path = './*' files = glob.glob(path) for name in files: print name
a = ( 1, "hello", 3)
b = ( some, where)
c = "6 scared of 7", "as 7 8 9" #notice can omit paren's
d = () # 0-tuple
e = 'yo', #one tuple 
f = ('yo',) #same one tuple
g = (d,) # g is ((),)
c = (4, 5) a, b = c
my_set = set([3, 9, 2, 6])
another_set = set("goodness") # set of unique chars
print another_set # set(['e', 'd', 'g', 'o', 'n', 's'])
if 'e' in another_set:
    print "it's in there" 
a = my_set; b = another_set;
c = a | b # union of sets
c = a & b # intersection of sets
c = a - b # difference of sets
c = a ^ b # symmetric difference of sets
another_set.add('y') # adds a single element to set
another_set.update([6,7,8]) # add multiple elements
my_set.remove(3) # removes the number 3 from my_set 
person = {
    "name" : "bob",
    "age" : 27,
    "sex" : "Male"
}
empty_dict = {} #an empty dictionary # or use dict()
name= person["name"] person["age"] = 28 person["address"] = "somewhere" #this would add a key-value pair del person["age"] # removes key value associated with 'age'
if "name" in person:
   name = person["name"]
else:
   name = "no one"
#the above conditional can be shortened to:
name = person.get("name", "no one")
keys = list(person) #keys is ['address', 'name', 'sex'] #could also do person.keys() #person.values() would get list of values #person.len() gives the number of keys in dictionary
while condition:
    statement1
    statement2
    ...
for n in [1,2,3,4,5,6,7,8,9]:
    print "2 to the %d  is %d" % (n, 2**n)
for n in range(1,10):
    print "2 to the %d  is %d" % (n, 2**n) # same as before
a = range(5) # can omit start to get a = 0, 1, 2, 3, 4 b = range(1,8) # b = 1, 2, 3, 4, 5, 6, 7 c = range(0, 13, 2) # c = 0, 2, 4, 6, 8, 10, 12 d = range(7, 2, -1) # d = 7, 6, 5, 4, 3
a = "Get rich quick"
for b in a:
    print b
c = ["now", "I", "know"]
for d in c:
    print c
person = {
    "name" : "bob",
    "age" : 27,
    "sex" : "Male"
}
for key in person:
    print key, person[key]
f = open("my_file.txt")
for line in f
    print line
Which of the following is true?
def smaller_value( a, b): if a < b: return a # notice single line if can be same line else: return b
print smaller_value(8, 4)
def reverse_list(list):
    if list == []: return []
    return reverse_list(list[1:]) + [list[0]]
print reverse_list([1, 2, 3, 4]) # prints [4, 3, 2, 1]
def divide(a,b):
   q = a // b
   r = a - q*b
   return (q, r)
quotient, remainder = divide(2373, 16)
def expify(a, b=2): return b**a #if don't give a second argument b will be 2
i = 5 def printi(): i=4 print i printi() # outputs 4 print i #outputs 5 #note without the i=4 assignment would get i=5
def assign_i(): global i i=3 assign_i() print i #now get 3
a = printi a() # prints 4
Consider:
def f(x): return x**3
f(10) #returns 1000
g = lambda x: x**3 #notice don't use return with lambda
g(10) #returns 1000 # lambda only works if  after : have an expression
#we can supply a function as arguments to other functions
def a(x):
    if x >= 0: return 1
    else: return 0;
def threshold (w, x, activation) :
    l = len(x)
    inner = 0;
    for i in range(0, l):
       inner += w[i] * x[i]
    return activation(inner)
w = [1, 2]
x = [1, 0]
threshold (w, x, a) # returns 1
# we can also return functions from functions
def make_adder (n): return lambda x: x + n
f = make_adder(2)
g = make_adder(6)
print f(42), g(42)
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
class Stack(object): #this says stack inherits from object
    a_class_variable = 5 # this var behaves like a Java static var
    def __init__(self): #self = this in Java
        self.stack = [] #now stack is a field variable of Stack
        #in general using self.field_var is how we declare and 
        #instantiate a instance variable
    def push(self, object): #the first argument of any method 
        self.stack.append(object) # is the object itself
    def pop(self):
        return self.stack.pop()
    @property #properties are computed attributes
    def length(self):
        return len(self.stack) 
    #(where an attribute is like a field) of a class
    # Can use dot notation with or without parentheses to invoke
    #@property is an example of a Python decorator which is a syntactic
    #which says this function object immediately after its definition should be
    #passed to the property() function to get additional features
my_instance = Stack()
my_instance.push("hello")
print my_instance.length
print isinstance(my_instance, object) #returns True
print issubclass(Stack, object) #returns True
#type(my_instance) returns something containing the word Stack
...
#etc
class Stack(list):
    def push(self, object):
        #could refer to parent by using syntax list.some_method_of_list
        #or use super(list, self).some_method_of_list
        self.append(object)
class MyClass:
   @staticmethod
   def my_method():
      #some code
MyClass.my_method() #similar to Java
#load in abstract class module
from abc import ABCMeta, abstractmethod, abstractproperty
class MyClass:
    __metaclass__ = ABCMeta # a metaclass is a class object that knows how to
                            # create other class objects. The default metaclass
                            # is type (Python 3, types.ClassType in Python 2). 
                            # Here we are assigning ABCMeta
                            # to be used rather than type
                            # In Python 3, write MyClass(metaclass=ABCmeta)
    @abstractmethod
    def my_abstract_method(self):
       pass
    @abstractproperty
    def my_abstract_property(self):
       pass
    try:
        statement_block_0
    except SomeError1 as error_name1:
        statement_block_1 #executed if a SomeError1 occurs
    except SomeError2 as error_name2:
        statement_block_2
    ...
    finally:
        statement_block_n # always gets executed
    try:
      f = open("file.txt", "r")
    except IOError as e:
      print e
    raise RuntimeError("Something bad just happened")
class MyException(exception): pass
#now could use as:
raise MyException("Whoa! A MyException occurred!")
#more control can be had by overriding __init__
#here we define an exception taking two arguments
class MyException2(exception):
    def __init__(self, errno, msg):
        self.args = (errno, msg)
        self.errno = errno
        self.errmsg = msg
raise MyException2(403, "Access Forbidden")
import div #notice not div.py a, b = div.divide(198, 15) #notice function in div.py have to be prefixed with div.
import div as foo #now foo is the prefix
from div import divide #from div import *; would import all functions print divide(198, 15)
def fact(n):
    "This function computes a factorial" #can use triple quoted strings
    if(n <= 1): return 1
    else: return n * fact(n - 1)
print fact.__doc__
import test help(test.fact)This would go to a screen that prints the documentation string.
pydoc test.factand get the same result as help(test.fact) before