Sign in

Intro to Computer Science

Unit 7

Functions

5 topics · 21 practice questions · Free responseNot yet reviewed

Notes

Defining and calling

  • def name(parameters): defines a function; the indented body runs only when you call it with name(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

  • return sends a value back and ends the function. A function with no return gives back None. print shows 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

What does the code def add(a, b): return a + b followed by print(add(3, 4)) display?
In def total(price, tax): ..., which of these is an argument in the call total(20, 3)?
What does def area(w, h=2): return w * h give for area(5)?
What does def f(): print("A"), then x = f(), then print(x) display?
A variable score is created inside a function. Where can it be used?
Which is the main advantage of writing a function instead of copying the same 5 lines in many places?

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: