Final Review Session - Part 2
Final Review Session - Part 2
Topics:
– Classes, inheritance
– Exceptions
– Functions
– Recursion
Classes: basics
(vehicle.py)
• Class definitions consist of data attributes
(variables) and method attributes (functions)
class Vehicle(object):
nextIdNum = 1 # this is a data attribute
myVehicle = Vehicle()
– attribute references
• uses dot notation to access attributes
class Vehicle(object):
nextIdNum = 1
def __init__(self):
self.idNum = nextIdNum
Vehicle.nextIdNum += 1
def honk(self):
print “HONK!”
class Vehicle(object):
nextIdNum = 1
def __init__(self):
self.idNum = Vehicle.nextIdNum
Vehicle.nextIdNum += 1
def honk(self):
print “HONK!”
def getIdNum(self):
return self.idNum
myVehicle = Vehicle()
print myVehicle.idNum # this prints an instance variable
Classes: inheritance
• Subclasses inherit from a superclass
– Subclass inherits all attributes (data and method) of superclass
– Subclass can also:
• Add new attributes
• Override attributes of the superclass
class Car(Vehicle):
# this is a new method attribute
def openDoor(self):
self.isDoorOpen = True
class Bicycle(Vehicle):
pass
raise ValueError
try:
if(type(c)!=str):
raise TypeError("I'm a type error argument!")
state = cities[c]
print "The city",c,"is in",state,"state"
except KeyError:
print c,"does not exist in cities dictionary!"
except TypeError:
print c,"is not a string!"
except:
print "Unknown error!"
findStateOfCity('Cambridge')
findStateOfCity('Seattle')
findStateOfCity(3)
Classes and exceptions example
See dice.py
Functions: invocation
• Q: What happens when you invoke (call) a
function?
• A: Values of actual parameters (arguments) are
assigned to the formal parameters
a = 10
b = 15
gcd(a,b) # a and b are actual parameters
Functions: return statements
• Ways to write return statements in Python
(the last 3 are equivalent):
– return <value>
– return None
– return
– <nothing>
Functions: scoping
• What is a scope?
– A scope or namespace is a space where variables
exist
– The scope of a variable determines where the
variable can be accessed from
Functions: scoping
• Each .py file has a global scope that spans the
entire file
• Each function inside the file defines a new
name space or scope
Global scope
Function B’s scope
print L # OK
myFunc’s scope myOtherFunc’s
scope
def myOtherFunc():
a = ‘hi’ a=3 a = ‘hi’
print L # OK
print b # error b=5 print b
print L
Code in myOtherFunc
print a # error is outside of myFunc’s
scope so it cannot see
names in myFunc’s
scope
Functions: scoping example #2
• CAN read outside variables from inside a function’s
scope
a = 3 # a exists in global scope
b = 5
def myFunc():
b = 4 # this just creates a new
# variable b in myFunc’s
# scope
myFunc()
print b # prints 5
Functions: scoping example #4
• CAN mutate an outside object
L = [1,2,3]
def myFunc():
L.append(0)
myFunc()
print L
Functions: scoping example #5
(colors.py)
def makeLighter(c):
def isPrimary():
if(c == "red" or c == "yellow" or c == "blue"):
# note that c belongs to the enclosing function's scope
return True
else:
return False
if isPrimary():
color = "light " + c #Q: are we writing to the color variable outside?
return color
elif(c == "black"):
color = "gray"
return color
color = "red"
print makeLighter(color),"is lighter than",color
color = "black"
print makeLighter(color),"is lighter than",color
color = "white"
print makeLighter(color),"is lighter than",color
#Q: Why does this say None? think about return types...
Recursion
• A recursive function always has
– at least one base case
– at least one recursive case
• Approaches to recursion
– Base case?
• look for the simplest version of the problem, which should
have a simple answer
– Recursive case?
• how do you call the function again with a simpler input?
(simpler usually means smaller or shorter)
– Do these recursive and base cases work to solve the
problem?
Recursion problem #1
(palindrome.py)
• Q: write a recursive function that checks if string s is a palindrome
• Note: there are often multiple ways to write a recursive solution! I think #1 is
more intuitive, but #2 is what is given in the textbook. Both solutions work.
• A #1:
def isPalindrome(s):
# 3 base cases
if len(s)==1:
return True
elif len(s)==2 and s[0]==s[1]:
# we will hit this if e.g. s=‘aa’
return True
elif len(s)==2 and not s[0]==s[1]:
# we will hit this if e.g. s=‘ab’
return False
• A:
def count_stair_ways(n):
# 2 base cases
if n==1:
return 1
elif n==2:
return 2
# recursive case
return count_stair_ways(n-1) + count_stair_ways(n-2)