Chapter 4: Functions 1
Functions
4.1 Introduction
4.1 Q1: Which of the following statements is false?
a. Experience has shown that the best way to develop and maintain a large pro-
gram is to construct it from a small number of large, proven pieces—this tech-
nique is called divide and conquer.
b. Using existing functions as building blocks for creating new programs is a key
aspect of software reusability—it’s also a major benefit of object-oriented pro-
gramming.
c. Packaging code as a function allows you to execute it from various locations in
your program just by calling the function, rather than duplicating the possibly
lengthy code.
d. When you change a function’s code, all calls to the function execute the updated
version.
4.2 Defining Functions
4.2 Q1: Which of the following statements is false?
a. Each function should perform a single, well-defined task.
b. The following code calls function square twice. We’ve replaced each of the out-
put values with ???. The first call produces the int value 49 and the second call
produces the int value 6:
In [1]: def square(number):
…: “””Calculate the square of number.””“
…: return number ** 2
…:
In [2]: square(7)
Out[2]: ???
In [3]: square(2.5)
Out[3]: ???
c. The statements defining a function are written only once, but may be called “to
do their job” from many points in a program and as often as you like.
2 Chapter 4: Functions
d. Calling square with a non-numeric argument like ‘hello’ causes a TypeEr-
ror because the exponentiation operator (**) works only with numeric values.
4.2 Q2: Which of the following statements is false?
a. A function definition begins with the def keyword, followed by the function
name, a set of parentheses and a colon (:).
b. Like variable identifiers, by convention function names should begin with a
lowercase letter and in multiword names underscores should separate each
word.
c. The required parentheses in a function definition contain the function’s param-
eter list—a comma-separated list of parameters representing the data that the
function needs to perform its task.
d. The indented lines after the colon (:) are the function’s suite, which consists of
an optional docstring followed by the statements that perform the function’s task.
4.2 Q3: Which of the following statements is false?
a. The following return statement first terminates the function, then squares
number and gives the result back to the caller:
return number ** 2
b. Function calls can be embedded in expressions.
c. The following code calls square first, then print displays the result:
print(‘The square of 7 is’, square(7))
d. Executing a return statement without an expression terminates the function
and implicitly returns the value None to the caller. When there’s no return state-
ment in a function, it implicitly returns the value None after executing the last
statement in the function’s block.
4.2 Q4: Which of the following statements is false?
a. Variables can be defined in a function’s block.
b. A function’s parameters and variables are all local variables. They exist only
while the function is executing and can be used only in that function.
c. Trying to access a local variable outside its function’s block causes a NameEr-
ror, indicating that the variable is not defined.
Chapter 4: Functions 3
d. All of the above statements are true.
4.3 Functions with Multiple Parameters
4.3 Q1: Which of the following statements a), b) or c) is false?
a. The following session defines a maximum function that determines and returns
the largest of three values—then calls the function three times with integers,
floating-point numbers and strings, respectively.
In [1]: def maximum(value1, value2, value3):
…: “””Return the maximum of three values.”””
…: max_value = value1
…: if value2 > max_value:
…: max_value = value2
…: if value3 > max_value:
…: max_value = value3
…: return max_value
…:
In [2]: maximum(12, 27, 36)
Out[2]: 36
In [3]: maximum(12.3, 45.6, 9.7)
Out[3]: 45.6
In [4]: maximum(‘yellow’, ‘red’, ‘orange’)
Out[4]: ‘yellow’
b. You also may call maximum with mixed types, such as ints and floats:
In [5]: maximum(13.5, -3, 7)
Out[5]: 13.5
c. The call maximum(13.5, ‘hello’, 7) results in TypeError because strings
and numbers cannot be compared to one another with the greater-than (>) oper–
ator.
d. All of the above statements are true.
4.3 Q2: Which of the following statements a), b) or c) is false?
a. The built-in max and min functions know how to determine the largest and
smallest of their two or more arguments, respectively.
4 Chapter 4: Functions
b. The built-in max and min functions also can receive an iterable, such as a list
but not a string.
c. Using built-in functions or functions from the Python Standard Library’s mod–
ules rather than writing your own can reduce development time and increase
program reliability, portability and performance.
d. All of the above statements are true.
4.4 Random-Number Generation
4.4 Q1: Which of the following statements is false?
a. You can introduce the element of chance via the Python Standard Library’s
random module.
b. The following code produces 10 random integers in the range 1–6 to simulate
rolling a six-sided die:
import random
for roll in range(10):
print(random.randrange(1, 7), end=‘ ‘)
c. Different values are likely to be displayed each time you run the code in Part
(b).
d. Sometimes, you may want to guarantee reproducibility of a random se-
quence—for debugging, for example. You can do this with the random module’s
repeat function.
4.4 Q2: Which of the following statements a), b) or c) is false?
a. If randrange truly produces integers at random, every number in its range has
an equal probability (or chance or likelihood) of being returned each time we call
it.
b. We can use Python’s underscore (_) digit separator to make a value like
6000000 more readable as 6_000_000.
c. The expression range(6,000,000) would be incorrect. Commas separate ar-
guments in function calls, so Python would treat range(6,000,000) as a call to
range with the three arguments 6, 0 and 0.
d. All of the above statements are true.
6 Chapter 4: Functions
d. Each local variable is accessible only in the block that defined it.
4.5 Q2: Which of the following statements is false?
a. The in operator in the following expression tests whether the tuple (7, 11)
contains sum_of_dice’s value. The operator’s right operand can be any iterable:
sum_of_dice in (7, 11)
b. There’s also a not in operator to determine whether a value is not in an itera-
ble.
c. The concise condition in Part (a) is equivalent to
(sum_of_dice = 7) or (sum_of_dice = 11)
d. All of the above statements are true.
4.6 Python Standard Library
4.6 Q1: Which of the following statements is false?
a. A key programming goal is to avoid “reinventing the wheel.”
b. A module is a file that groups related functions, data and classes.
c. A package groups related modules. Every Python source-code (.py) file you
create is a module. They’re typically used to organize a large library’s functional-
ity into smaller subsets that are easier to maintain and can be imported sepa-
rately for convenience.
d. The Python Standard Library module money provides arithmetic capabilities
for performing monetary calculations.
4.7 math Module Functions
4.7 Q1: Which of the following statements is false?
a. An import statement of the following form enables you to use a module’s defi-
nitions via the module’s name and a dot (.):
import math
Chapter 4: Functions 7
b. The following snippet calculates the square root of 900 by calling the math
module’s sqrt function, which returns its result as a float value:
math.sqrt(900)
c. The following snippet calculates the absolute value of –10 by calling the math
module’s fabs function, which returns its result as a float value:
math.fabs(–10)
d. The value of the expression floor(–3.14159) is –3.0.
4.8 Using IPython Tab Completion for Discovery
4.8 Q1: Which of the following statements a), b) or c) is false?
a. You can view a module’s documentation in IPython interactive mode via tab
completion—a discovery feature that speeds your coding and learning processes.
b. After you type a portion of an identifier and press Tab, IPython completes the
identifier for you or provides a list of identifiers that begin with what you’ve typed
so far.
c. IPython tab completion results may vary based on your operating system plat-
form and what you have imported into your IPython session.
d. All of the above statements are true.
4.8 Q2: Which of the following statements is false?
a. To view a list of identifiers defined in a module, type the module’s name and a
dot (.), then press Tab.
b. In the math module, pi and e represent the mathematical constants and e,
respectively.
c. Python does not have constants, so even though pi and e are real-world con-
stants, you must not assign new values to them, because that would change their
values.
d. To help distinguish “constants” from other variables, the Python style guide
recommends naming your custom constants with a leading underscore (_) and a
trailing underscore.
4.9 Default Parameter Values
4.9 Q1: Which of the following statements is false?
8 Chapter 4: Functions
a. When defining a function, you can specify that a parameter has a default pa-
rameter value.
b. When calling the function, if you omit the argument for a parameter with a de-
fault parameter value, the default value for that parameter is automatically
passed.
c. The following defines a function rectangle_area with default parameter val-
ues:
def rectangle_area(length=2, width=3):
“””Return a rectangle’s area.”“”
return length * width
d. The call rectangle_area() to the function in Part (c) returns the value 0
(zero).
4.9 Q2: Assuming the following function definition, which of the following state-
ments is false?
def rectangle_area(length=2, width=3):
“””Return a rectangle’s area.”“”
return length * width
a. You specify a default parameter value by following a parameter’s name with an
= and a value.
b. Any parameters with default parameter values must appear in the parameter
list to the right of parameters that do not have defaults.
c. For the following call, the interpreter passes the default parameter value 3 for
the width as if you had called rectangle_area(3, 10):
rectangle_area(10)
d. The following call to rectangle_area has arguments for both length and
width, so IPython ignores the default parameter values:
rectangle_area(10, 5)
4.10 Keyword Arguments
4.10 Q1: Based on the following function definition:
Chapter 4: Functions 9
def rectangle_area(length, width):
“””Return a rectangle’s area.”“”
return length * width
Which of the following statements based on this function definition is false?
a. Each keyword argument in a call has the form parametername=value.
b. The following call shows that the order of keyword arguments matters—they
need to match the corresponding parameters’ positions in the function definition:
rectangle_area(width=5, length=10)
c. In each function call, you must place keyword arguments after a function’s po-
sitional arguments—that is, any arguments for which you do not specify the pa-
rameter name. Such arguments are assigned to the function’s parameters left–to–
right, based on the argument’s positions in the argument list.
d. Keyword arguments can improve the readability of function calls, especially for
functions with many arguments.
4.11 Arbitrary Argument Lists
4.11 Q1: Which of the following statements a), b) or c) is false?
a. The min function’s documentation states that min has two required parameters
(named arg1 and arg2) and an optional third parameter of the form *args, in-
dicating that the function can receive any number of additional arguments.
b. The following is a valid call to function min
min(88)
c. The * before the parameter name *args in Part (a) tells Python to pack any
remaining arguments into a tuple that’s passed to the args parameter.
d. All of the above statements are true.
4.11 Q2: Based on the following function definition that can receive an arbitrary
number of arguments:
In [1]: def average(*args):
…: return sum(args) / len(args)
…:
Which of the following statements a), b) or c) is false?
a. The parameter name args is used by convention, but you may use any identi-
fier.
10 Chapter 4: Functions
b. If the function has multiple parameters, the *args parameter must be the left-
most one.
c. The following session calls average several times confirming that it works with
arbitrary argument lists of different lengths:
In [2]: average(5, 10)
Out[2]: 7.5
In [3]: average(5, 10, 15)
Out[3]: 10.0
In [4]: average(5, 10, 15, 20)
Out[4]: 12.5
d. All of the above statements are true.
4.12 Methods: Functions That Belong to Objects
4.12 Q1: Which of the following statements a), b) or c) is false?
a. A method is simply a function that you call on an object using the form
object_name.method_name(arguments)
b. The following session calls the string object s’s lower and upper methods,
which produce new strings containing all-lowercase and all-uppercase versions
of the original string, leaving s unchanged:
In [1]: s = ‘Hello’
In [2]: s.lower() # call lower method on string object s
Out[2]: ‘hello’
In [3]: s.upper()
Out[3]: ‘HELLO’
c. After the preceding session, s contains ‘HELLO’.
d. All of the above statements are true.
4.13 Scope Rules
4.13 Q1: Which of the following statements a), b) or c) is false?
Chapter 4: Functions 11
a. Each identifier has a scope that determines where you can use it in your pro-
gram. For that portion of the program, the identifier is said to be “in scope.”
b. A local variable’s identifier has local scope. It’s “in scope” only from its defini-
tion to the end of the program. It “goes out of scope” when the function returns to
its caller.
c. A local variable can be used only inside the function that defines it.
d. All of the above statements are true.
4.13 Q2: Which of the following statements a), b) or c) is false?
a. Identifiers defined outside any function (or class) have script scope—these may
include functions, variables and classes.
b. Variables with global scope are known as global variables.
c. Identifiers with global scope can be used in a .py file or interactive session
anywhere after they’re defined.
d. All of the above statements are true.
4.13 Q3: Which of the following statements a), b) or c) is false?
a. You can access a global variable’s value inside a function.
b. By default, you cannot modify a global variable in a function—when you first
assign a value to a variable in a function’s block, Python creates a new local vari-
able.
c. To modify a global variable in a function’s block, you must use a global state-
ment to declare that the variable is defined in the global scope.
d. All of the above statements are true.
4.14 import: A Deeper Look
4.14 Q1: Which of the following statements is false?
a. You can import all identifiers defined in a module with a wildcard import of the
form
from modulename import *
b. A wildcard import makes all of the module’s identifiers available for use in your
code.
12 Chapter 4: Functions
c. Importing a module’s identifiers with a wildcard import can lead to subtle er-
rors—it’s considered a dangerous practice that you should avoid.
d. The following session is a safe use of a wildcard import:
In [1]: e = ‘hello’
In [2]: from math import *
In [3]: e
Out[3]: 2.718281828459045
4.14 Q2: Which of the following statements is false?
a. Sometimes it’s helpful to import a module and use an abbreviation for it to sim-
plify your code. The import statement’s as clause allows you to specify the name
used to reference the module’s identifiers. For example, we can import the sta-
tistics module and access its mean function as follows:
In [1]: import statistics as stats
In [2]: grades = [85, 93, 45, 87, 93]
In [3]: stats.mean(grades)
Out[3]: 80.6
b. import…as is frequently used to import Python libraries with convenient ab-
breviations, like stats for the statistics module.
c. The numpy module is typically imported with
import numpy as npy
d. Typically, when importing a module, you should use import or import…as
statements, then access the module through the module name or the abbreviation
following the as keyword, respectively. This ensures that you do not accidentally
import an identifier that conflicts with one in your code.
14 Chapter 4: Functions
d. All of the above statements are true.
4.16 Q2: Which of the following statements is false?
a. Most functions have one or more parameters and possibly local variables that
need to exist while the function is executing, remain active if the function makes
calls to other functions, and “go away” when the function returns to its caller.
b. A called function’s stack frame is the perfect place to reserve memory for the
function’s local variables.
c. A called function’s stack frame is popped when the function is called and exists
while the function is executing.
d. When a function returns, it no longer needs its local variables, so its stack frame
is popped from the stack, and its local variables no longer exist.
4.17 Functional-Style Programming
4.17 Q1: Which of the following statements a), b) or c) is false?
a. Like other popular languages, such as Java and C#, Python is a purely functional
language.
b. Functional-style programs can be easier to parallelize to get better perfor-
mance on today’s multi-core processors.
c. You’ve already used list, string and built-in function range iterators with the
for statement, and you’ve used iterators with several reductions (functions sum,
len, min and max).
d. All of the above statements are true.
4.17 Q2: Which of the following statements about functional-style programming
is false?
a. It lets you simply say what you want to do. It hides many details of how to per-
form each task.
b. Typically, library code handles the how for you. This can eliminate many errors.
c. Consider the for statement in many other programming languages. Typically,
you must specify all the details of counter-controlled iteration: a control variable,
its initial value, how to increment it and a loop-continuation condition that uses
Chapter 4: Functions 15
the control variable to determine whether to continue iterating. This style of iter-
ation is known as external iteration and is error-prone.
d. Functional-style programming emphasizes mutability—it uses only operations
that modify variables’ values.
4.17 Q3: Which of the following statements is false?
a. In pure functional programming languages you focus on writing pure functions.
A pure function’s result depends only on the argument(s) you pass to it. Also,
given particular arguments, a pure function always produces the same result. For
example, built-in function sum’s return value depends only on the iterable you
pass to it.
b. Pure functions can have side effects—for example, if you pass a mutable list to
a pure function, the list can contain different values before and after the function
call.
c. The following session demonstrates that when you call the pure function sum,
it does not modify its argument.
In [1]: values = [1, 2, 3]
In [2]: sum(values)
Out[2]: 6
In [3]: sum(values) # same call always returns same result
Out[3]: 6
In [4]: values
Out[4]: [1, 2, 3]
d. Functions are objects that you can pass to other functions as data.
4.18 Intro to Data Science: Measures of Dispersion
4.18 Q1: Which of the following statements is false?
a. When we’re talking about a group, the entire group is called the population.
b. Sometimes a population is quite large, such as the people likely to vote in the
next U.S. presidential election—in excess of 100,000,000 people.
c. For practical reasons, polling organizations trying to predict who will become
the next president work with carefully selected small subsets of the population
16 Chapter 4: Functions
known as samples. Many of the polls in the 2016 election had sample sizes of
about 1000 people.
d. Measures of dispersion help you understand how concentrated the values are.
4.18 Q2: Which of the following statements a), b) or c) is false?
a. The standard deviation is the square root of the variance, which tones down
the effect of the outliers.
b. The smaller the variance and standard deviation are, the further the data values
are from the mean and the greater overall dispersion (that is, spread) there is
between the values and the mean.
c. The following code calculates the population standard deviation with the sta-
tistics module’s pstdev function:
statistics.pstdev([1, 3, 4, 2, 6, 5, 3, 4, 5, 2])
d. All of the above statements are true.