4Functions
Objectives
In this chapter, you’ll
Create custom functions.
generation.
Seed the random number
generator to ensure
reproducibility.
Pack values into a tuple and
arguments.
Create functions that can
receive any number of
arguments.
Use methods of an object.
PyCDS_04_Functions.fm Page 1 Thursday, February 20, 2020 9:28 AM
Note: Throughout the Instructor Solutions Manual, solutions are not provided for project,
research and challenge exercises—many of which are substantial and appropriate for term
projects, directed-study projects, capstone-course projects and thesis topics. Before assign-
ing a particular exercise for homework, instructors should check the IRC to be sure the
Exercises
Unless specified otherwise, use IPython sessions for each exercise.
4.1 (Discussion: else Clause) In the script of Fig. 4.1, we did not include an else
clause in the ifelif statement. What are the possible consequences of this choice?
4.2 (Discussion: Function-Call Stack) What happens if you keep pushing onto a stack,
without enough popping?
Answer: A limited amount of memory gets allocated for use by the function call
4.3 (What’s Wrong with This Code?) What is wrong with the following cube func-
tion’s definition?
def cube(x):
“””Calculate the cube of x.”””
x ** 3
print(‘The cube of 2 is’, cube(2))
4.4 (What’s Does This Code Do?) What does the following mystery function do? As-
sume you pass the list [1, 2, 3, 4, 5] as an argument.
def mystery(x):
y = 0
for value in x:
y += value ** 2
return y
4.18 (Functional-Style Programming: Internal vs. External Iteration) Why is internal
iteration preferable to external iteration in functional-style programming?
Exercises 3
4.19 (Functional-Style Programming: What vs. How) Why is programming that em-
phasizes “what” preferable to programming that emphasizes “how”? What is it that makes
“what” programming feasible?
Answer: Programming that emphasizes “whatis preferable to programming that