Computer Science 15-110, Fall 2010
Class Notes: Writing Functions
Writing Functions
def minSquared(x,y):
smaller = min(x,y)
return smaller*smaller
print minSquared(3,4)
print minSquared(4,3)
Another example:
# This function computes the area in the first quadrant under
# the line y=mx+b. It assumes m is negative and b is positive,
# so we in fact have a triangle in the first quadrant.
def areaUnderLine(m, b):
# The x-intercept of y=mx+b is where y=0, so mx+b=0, so x=-b/m
width = -b/m
# b is the y-intercept
height = b
# now we have the width and height of the right triangle
# under the line in the first quadrant, so...
return width*height/2
print "Area under y=-2x+8 is: " + str(areaUnderLine(-2,8))
Yet another example:
def isEvenPositive(x):
isEven = ((x % 2) == 0)
isPositive = (x > 0)
return (isEven and isPositive)
print(isEvenPositive(-2))
print(isEvenPositive(-1))
print(isEvenPositive(0))
print(isEvenPositive(1))
print(isEvenPositive(2))
And yet another example:
def initials(firstName, lastName):
firstInitial = firstName[0]
lastInitial = lastName[0]
return firstInitial + lastInitial
print initials("Donald", "Knuth")
carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem - carpe diem