Autosaved
Autosaved
Python
What Are Functions?
• Reusability
• Fewer errors introduced when code isn’t rewritten
• Reduces complexity of code
• Programs are easier to maintain
• Programs are easier to understand
Function Elements
identifier
Formal Don’t forget the colon :
keyword
parameters or to mark the start of a
arguments statement bloc
Function body
• The colon at the end of the definition head marks the start of the
body, the bloc of statements. There is no symbol to mark the end of
the bloc, but remember that indentation in Python controls
statement blocs.
• def average(total, num):
x = total/num
return x
Function body
• Using the small function defined in the last slide, write a command
line program which asks the user for a test score total and the
number of students taking the test. The program should print the test
score average.
Happy Birthday Example:
Function Flow
• # happy.py
• # Simple illustration of functions.
• def happy():
• print "Happy Birthday to you!"
• def sing(person):
• happy()
• happy()
• print "Happy birthday, dear", person + "."
• happy()
• def main():
• sing("Fred")
• print
• sing("Lucy")
• print
• sing("Elmer")
•
• main()
Functions: Formal vs. Actual
Paramaters (and Arguments)
• # moveto.py
Formal Parameters
• from graphics import *
• def moveTo(object, point):
Function definition
• c = object.getCenter()
• dx = point.getX() - c.getX()
• dy = point.getY() - c.getY()
• object.move(dx,dy)
Actual parameters or
• def main(): arguments
• win = GraphWin()
• circ = Circle(Point(100,100), 20)
• circ.draw(win)
• p = win.getMouse()
Call or invocation of function;
• moveTo(circ, p)
Arguments must be in correct
• win.close() order according to function
• center = circ.getCenter() definition
• print center.getX(), center.getY()
• main()
Scope of variables
• Variables are “valid” only within the function in which they are
declared/initialized. The scope of the variable is LOCAL. Only when a
variable is passed as a parameter to a function can another function
“see” or use the variable—and then only its value.
• Thus it is possible to have two variables named the same within one
source code file, but they will be different variables if they’re in
different functions—and they could be different data types as well.
Scope of variables, cont.
x has scope only in calc_tax function
• def calc_tax(x):
x = x * 0.08
return x
def add_shipping(subtot):
subtot has local scope only
subtot = subtot * 1.04
return subtot
def main():
units = input(“Please enter the # of units”)
firstTotal = units * 5.00 Invocation/call
total = add_shipping(firstTotal)
total = total + calc_tax(total)
print “Your total is: “, total
firstTotal is sent as a parameter,
main() and returns a value stored in total
Functions: Return values
• Some functions don’t have any parameters or any return values, such
as functions that just display. See Happy Birthday ex. above. But…
• “return” keyword indicates what value(s) will be kicked back after a
function has been invoked
• def square(x):
Formal parameter
return x * x
The call: output = square(myNum) Return value
Return value used as argument:
Example of calculating a hypotenuse
• num1 = 10
• num2 = 14
• Hypotenuse = math.sqrt(sum_of_squares(num1, num2))
• def sum_of_squares(x,y)
t = (x*x) + (y * y)
return t
Triangle2.py example
• Triangle2.py
• Text of triangle2.py
• Task: Create a user-defined function that
calculates the factorial of a number.
o The function should take an integer as an
argument and return its factorial.
o Use recursion or a loop to compute the
factorial.
•Task 2 :
• Create two user-defined
functions: is_even() and is_odd().
Returning more than one value
def main():
units = input(“Please enter the # of
units”)
firstTotal = units * 5.00
total = add_shipping(firstTotal)
# total = total + calc_tax(total)
print “Your total is: “, total
main()The value returned by add_shipping() is stored in a new
variable, total, in main()
Example of flawed function call
• # addinterest1.py
• # Program illustrates failed attempt to change value of a parameter
• def test():
• amount = 1000
• rate = 0.05
• addInterest(amount, rate)
• print amount
•
• test()
Flawed function call corrected
• # addinterest2.py
• # Illustrates use of return to change value in calling program.
• def test():
• amount = 1000
• rate = 0.05
• amount = addInterest(amount, rate)
• print amount
• test()
Modifying parameters, cont.
1011001
firstTotal
add_shipping()
1011001
firstTotal
add_shipping()
25.90 Memory
location passed
Main()
to subfunction
Using memory
location, actual value
of original variable is
changed
Passing lists in Python
• def test():
• amounts = [1000, 2200, 800, 360]
• rate = 0.05
• addInterest(amounts, 0.05)
• print amounts
• test()
Passing lists, cont.
Photography