Notes
Defining and calling
def name(parameters):defines a function; the indented body runs only when you call it withname(arguments).- Parameters are the names in the definition. Arguments are the values passed in. They match by position. A default value (
exp=2) is used if no argument is given.
Return values and scope
returnsends a value back and ends the function. A function with noreturngives backNone.printshows a value but does not return it.- Local variables (including parameters) exist only inside their function. Global variables are defined outside functions.
Design
- Use functions to avoid repeating code, to name tasks clearly, and to test small pieces. Functions can call other functions.
def average(a, b):
return (a + b) / 2
print(average(4, 10))
This prints 7.0.
Topics in this unit
Each topic has its own short notes and practice.
Practice
def add(a, b): return a + b followed by print(add(3, 4)) display?The function returns 3 + 4 = 7.
def total(price, tax): ..., which of these is an argument in the call total(20, 3)?20 and 3 are the arguments; price and tax are parameters.
def area(w, h=2): return w * h give for area(5)?h uses the default value of 2, so 5 * 2 = 10.
def f(): print("A"), then x = f(), then print(x) display?The function prints A but returns None, so x is None.
score is created inside a function. Where can it be used?A variable created inside a function is local to it.
Reuse makes code shorter and easier to maintain.
Free response
Write your answer first, then open the scoring guide.
Free-response question
A student writes functions for a small shop program.
(a) Write a function named total_cost that takes price and quantity and returns the cost.
Show the answer and scoring guide
def total_cost(price, quantity):
return price * quantity
Check off the points you earned:
(b) Write a call that stores the cost of 3 items priced at 4 in a variable named cost, then prints it. What is printed?
Show the answer and scoring guide
cost = total_cost(4, 3)
print(cost)
The output is 12.
Check off the points you earned:
(c) Explain the difference between using print and return inside total_cost, and which is better for this function.
Show the answer and scoring guide
print only displays a value on the screen, while return gives the value back so it can be stored or used in more math. return is better because the caller can reuse the result.
Check off the points you earned: