Chapter 5 Functions
Chapter 5 Functions
5 Functions
TOPICS
5.1 Introduction to Functions 5.8 Writing Your Own Value-Returning
5.2 Defining and Calling a Void Function Functions
5.3 Designing a Program to Use Functions 5.9 The math Module
5.4 Local Variables 5.10 Storing Functions in Modules
5.5 Passing Arguments to Functions 5.11 Turtle Graphics: Modularizing Code
5.6 Global Variables and Global Constants with Functions
5.7 Introduction to Value-Returning
Functions: Generating Random Numbers
CONCEPT: A function is a group of statements that exist within a program for the
purpose of performing a specific task.
241
14 turtle.hideturtle()
15
16 # Draw a square.
17 my_graphics.square(X2, Y2, (X3 − X2), 'gray')
18
19 # Draw some circles.
20 my_graphics.circle(X1, Y1, RADIUS, 'blue')
21 my_graphics.circle(X2, Y2, RADIUS, 'red')
22 my_graphics.circle(X3, Y3, RADIUS, 'green')
23
24 # Draw some lines.
25 my_graphics.line(X1, Y1, X2, Y2, 'black')
26 my_graphics.line(X1, Y1, X3, Y3, 'black')
27 my_graphics.line(X2, Y2, X3, Y3, 'black')
28
29 # Call the main function.
30 if _ _name_ _ == '_ _main_ _':
31 main()
Review Questions
Multiple Choice
1. A group of statements that exist within a program for the purpose of performing a
specific task is a(n) __________.
a. block
b. parameter
c. function
d. expression
2. A design technique that helps to reduce the duplication of code within a program and
is a benefit of using functions is __________.
a. code reuse
b. divide and conquer
c. debugging
d. facilitation of teamwork
3. The first line of a function definition is known as the __________.
a. body
b. introduction
c. initialization
d. header
4. You __________ a function to execute it.
a. define
b. call
c. import
d. export
5. A design technique that programmers use to break down an algorithm into functions
is known as __________.
a. top-down design
b. code simplification
c. code refactoring
d. hierarchical subtasking
6. A __________ is a diagram that gives a visual representation of the relationships
between functions in a program.
a. flowchart
b. function relationship chart
c. symbol chart
d. hierarchy chart
7. The _____________ keyword is ignored by the Python interpreter and can be used as
a placeholder for code that will be written later.
a. placeholder
b. pass
c. pause
d. skip
8. A __________ is a variable that is created inside a function.
a. global variable
b. local variable
c. hidden variable
d. none of the above; you cannot create a variable inside a function
9. A(n) __________ is the part of a program in which a variable may be accessed.
a. declaration space
b. area of visibility
c. scope
d. mode
18. This statement causes a function to end and sends a value back to the part of the pro-
gram that called the function.
a. end
b. send
c. exit
d. return
19. This is a design tool that describes the input, processing, and output of a function.
a. hierarchy chart
b. IPO chart
c. datagram chart
d. data processing chart
20. This type of function returns either True or False.
a. Binary
b. true_false
c. Boolean
d. logical
21. This is a math module function.
a. derivative
b. factor
c. sqrt
d. differentiate
True or False
1. The phrase “divide and conquer” means that all of the programmers on a team should
be divided and work in isolation.
2. Functions make it easier for programmers to work in teams.
3. Function names should be as short as possible.
4. Calling a function and defining a function mean the same thing.
5. A flowchart shows the hierarchical relationships between functions in a program.
6. A hierarchy chart does not show the steps that are taken inside a function.
7. A statement in one function can access a local variable in another function.
8. In Python, you cannot write functions that accept multiple arguments.
9. In Python, you can specify which parameter an argument should be passed into a func-
tion call.
10. You cannot have both keyword arguments and non-keyword arguments in a function call.
11. Some library functions are built into the Python interpreter.
12. You do not need to have an import statement in a program to use the functions in the
random module.
13. Complex mathematical expressions can sometimes be simplified by breaking out part
of the expression and putting it in a function.
14. A function in Python can return more than one value.
15. IPO charts provide only brief descriptions of a function’s input, processing, and output,
but do not show the specific steps taken in a function.
Short Answer
1. How do functions help facilitate teamwork?
2. Name and describe the two parts of a function definition.
3. When a function is executing, what happens when the end of the function block is
reached?
4. What is a local variable? What statements are able to access a local variable?
5. What scope do parameter variables have?
6. Why do global variables make a program difficult to debug?
7. Suppose you want to select a random number from the following sequence:
0, 5, 10, 15, 20, 25, 30
What library function would you use?
8. What statement do you have to have in a value-returning function?
9. Draw an IPO chart that documents the input, processing, and output of the built-in
input function.
10. What is a Boolean function?
11. What are the advantages of breaking a large program into modules?
Algorithm Workbench
1. Write a function named shout. The function should accept a string argument and
display it in uppercase with an exclamation mark concatenated to the end.
2. Examine the following function header, then write a statement that calls the function,
passing 12 as an argument.
def show_value(quantity):
3. Look at the following function header:
def my_function(a, b, c):
Now look at the following call to my_function:
my_function(3, 2, 1)
When this call executes, what value will be assigned to a? What value will be assigned
to b? What value will be assigned to c?
4. What will the following program display?
def main():
x = 1
y = 3.4
print(x, y)
change_us(x, y)
print(x, y)
def change_us(a, b):
a = 0
b = 0
print(a, b)
main()
5. Look at the following function definition:
def my_function(x, y):
return x[y]
a. Write a statement that calls this function and uses keyword arguments to pass
“testing” into x and 2 into y.
b. What will be printed when the function call executes?
6. Write a statement that generates a random number in the range of 1 through 100 and
assigns it to a variable named rand.
7. The following statement calls a function named half, which returns a value that is
half that of the argument. (Assume the number variable references a float value.)
Write code for the function.
result = half(number)
8. A program contains the following function definition:
def cube(num):
return num * num * num
Write a statement that passes the value 4 to this function and assigns its return value
to the variable result.
9. Write a function named times_ten that accepts a number as an argument. When the
function is called, it should return the value of its argument multiplied times 10.
10. Write a function named get_first_name that asks the user to enter his or her first
name, and returns it.
Programming Exercises
1. Kilometer Converter
Write a program that asks the user to enter a distance in kilometers, then converts that
VideoNote
The Kilometer distance to miles. The conversion formula is as follows:
Converter
Problem Miles 5 Kilometers 3 0.6214
2. String Repeater
Python allows you to repeat a string by multiplying it by an integer, for example, 'Hi' * 3
will give 'HiHiHi'. Pretend that this feature does not exist, and instead write a function
named repeat that accepts a string and an integer as arguments. The function should
return a string of the original string repeated the specified number of times, for example,
repeat('Hi', 3) should return 'HiHiHi'.
VideoNote
One foot equals 12 inches. Write a function named feet_to_inches that accepts a number
The Feet to of feet as an argument and returns the number of inches in that many feet. Use the function
Inches Problem
in a program that prompts the user to enter a number of feet then displays the number of
inches in that many feet.
11. Addition Test
Write a program that generates printable addition tests. The tests should consist of 5 questions
which present a simple addition question in the following format, where the question number
goes from 1 to 5, and num1 and num2 are randomly generated numbers between 1 and 10:
Question 1
num1 + num2 = _____
The program should simply display the 5 questions; it should not prompt the user for any
input.
12. Maximum of Two Values
Write a function named max that accepts two integer values as arguments and returns the
value that is the greater of the two. For example, if 7 and 12 are passed as arguments to
the function, the function should return 12. Use the function in a program that prompts the
user to enter two integer values. The program should display the value that is the greater
of the two.
The variables in the formula are as follows: KE is the kinetic energy, m is the object’s mass
in kilograms, and v is the object’s velocity in meters per second.
Write a function named kinetic_energy that accepts an object’s mass (in kilograms)
and velocity (in meters per second) as arguments. The function should return the amount
of kinetic energy that the object has. Write a program that asks the user to enter values
for mass and velocity, then calls the kinetic_energy function to get the object’s kinetic
energy.
15. Test Average and Grade
Write a program that asks the user to enter five test scores. The program should display a
letter grade for each score and the average test score. Write the following functions in the
program:
• calc_average. This function should accept five test scores as arguments and return the
average of the scores.
• determine_grade. This function should accept a test score as an argument and return
a letter grade for the score based on the following grading scale:
TIP: Recall that the % operator divides one number by another and returns the
remainder of the division. In an expression such as num1 % num2, the % operator will
return 0 if num1 is evenly divisible by num2.
• If one player chooses paper and the other player chooses rock, then paper wins.
(Paper wraps rock.)
• If both players make the same choice, the game must be played again to determine
the winner.
when the width and the height are the same.) When the program runs, the program should
ask the user for the width and height of the pattern, then pass these values as arguments to
the drawPattern function.