Date post: | 14-Dec-2015 |
Category: |
Documents |
Upload: | dylan-ashburn |
View: | 214 times |
Download: | 0 times |
Informal idea of a function
A function converts an input to an output The inputs are called actual parameters
or arguments The output is called the return value.
Input
function
output
Name: maxOf2
Input: two numbers Output: the value of the largest one Defining the function in Python
def maxOf2(n1, n2): # n1 and n2 are numbers #returns the largest
if n1 >= n2: return n1 else: return n2
Using the function
# Using a variable to “catch” the returned valueans = maxOf2(48, 35)print ansans1 =maxOf2(45.6, 78.3)print ans1
# Printing the returned value immediately# Note that sometimes the function may work for values of the actual # parameters that were not intended! Don’t count on it!
print maxOf2("Dan", "Don")print maxOf2([1,2,3], [4,5,6])
Maximum number in a list
Input: a list of numbers Output: the value of the largest number
in the list Algorithm:
Maximum number in a list
Input: a list of numbers Output: the value of the largest number
in the list Algorithm:
Let biggestSoFar be the first item in the list Loop through all items in the list
If you find some item larger than biggestSoFar, set biggestSoFar to this new value
#Defining the function in Python
def maxInList(aList): #aList is a non empty list of numbers #returns the largest item on the list
biggestSoFar = aList[0] for item in aList[1:]: if item > biggestSoFar: biggestSoFar = item return biggestSoFar
#Using the function#A variable to “catch” the returned valueans = maxInList( [2,65,98,44,5,21,50,64])print ans#Using the returned value directlyprint maxInList( ['Hal', 'Sally', 'George', 'Tim', 'Mike'])
Compute simple interest
Input: Principal, rate, years Output: The amount of interest earned
on the principal after the given number of years
Defining the function in Python
def simpleInterest(principal, rate, years): #rate is given as a decimal so a 2% annual rate #would be given as 0.02 #Returns the total amount of interest on the principate at rate #for this many years
interest = principal*rate*years return interest
#Using the function in Python
print simpleInterest(500, 0.03, 5)
Compound Interest
Input: principal, annual rate, number of compounding periods per year, number of years
Output: The total interest earned Algorithm:
Figure out the rate per compounding period Figure out the number of compounding
periods Compute the final value of the investment Compute and return the interest
#Defining the function in Pythondef compoundInterest(principal, rate, n, years): #returns the interest gained on the principal after years #where the interest is compounded n times per year #rate is the annual rate given as a decimal
#compute the number of compounding periods p = n * years #compute the interest rate per compounding period r = rate/n #calculate the final value of the investment value = principal for i in range(p): value = value + value*r #calculate the difference between the initial investment and #the current value interest = value - principal return interest
#Using the function in Pythonprint compoundInterest(500,0.03,12,5)
Find the distance between points Input: Two points (given as graphics
objects) Output: The distance between the
points Algorithm:
Find the distance between points Input: Two points (given as graphics
objects) Output: The distance between the
points Algorithm:
Find the x and y coordinates of the first point
Find the x and y coordinate of the second point
Use the distance formula to calculate the distance
Return the distance
#Define the functiondef distance(p1, p2): #p1 and p2 are Point objects #returns the distance between the points
x1 = p1.getX() y1 = p1.getY() x2 = p2.getX() y2 = p2.getY() dist = math.sqrt( (x1 - x2)**2 + (y1 - y2)**2) return dist
#Use the functionprint distance(Point(3,4), Point(0,0))
Tell if point is inside a circle
Input: Point object and Circle object Output: True or False depending on
whether the point is inside the circle Algorithm
Tell if point is inside a circle
Input: Point object and Circle object Output: True or False depending on
whether the point is inside the circle Algorithm
Get the center of the circle Get the radius of the circle Calculate the distance of the point to the
center of the circle If it is less that the radius return True Otherwise return False
#Defining the functiondef isInside(myPoint, myCircle): #returns True if myPoint is inside myCircle; otherwise False
p1 = myCircle.getCenter() r = myCircle.getRadius() dis = distance(myPoint,p1) #use the other function I defined if dis <=r: return True else: return False
#Using the functionwin = GraphWin("Testing Functions", 400, 400)win.setCoords (0,0,5,5)c = Circle(Point(2,3), 0.5)c.draw(win)c.setFill("yellow")p1 = Point(2,4)p1.draw(win)print isInside(p1, c)
Make a circle “blink” in new color Input: a Circle object, the current color,
a new color Output: Nothing to return Algorithm
Make a circle “blink” in new color Input: a Circle object, the current color,
a new color Output: Nothing to return Algorithm
set fill to new color Sleep for one minute Set fill to the original color
def flash (myCircle, oldColor, newColor): #expects a circle whose fillColor is oldColor #changes the color of myCircle to new color, waits 1 sec\ #and changes back to old color
myCircle.setFill(newColor) time.sleep(1) myCircle.setFill(oldColor) return
win = GraphWin("Testing Functions", 400, 400)win.setCoords (0,0,5,5)c = Circle(Point(2,3), 0.5)c.draw(win)c.setFill("yellow")p1 = Point(2,4)p1.draw(win)print isInside(p1, c)flash(c, "yellow", "green")time.sleep(1)flash(c, "yellow", 'pink')