Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
5 views14 pages

Chapter 5 Functions

Chapter 5 discusses functions in programming, defining them as groups of statements that perform specific tasks. It covers various topics including defining, calling, and designing functions, as well as the use of local and global variables. The chapter also includes review questions and programming exercises to reinforce the concepts learned.

Uploaded by

uphetheniphofu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

Chapter 5 Functions

Chapter 5 discusses functions in programming, defining them as groups of statements that perform specific tasks. It covers various topics including defining, calling, and designing functions, as well as the use of local and global variables. The chapter also includes review questions and programming exercises to reinforce the concepts learned.

Uploaded by

uphetheniphofu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

CHAPTER

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

5.1 Introduction to Functions

CONCEPT: A function is a group of statements that exist within a program for the
purpose of performing a specific task.

In Chapter 2, we described a simple algorithm for calculating an employee’s pay. In the


algorithm, the number of hours worked is multiplied by an hourly pay rate. A more realistic
payroll algorithm, however, would do much more than this. In a real-world application,
the overall task of calculating an employee’s pay would consist of several subtasks, such as
the following:
• Getting the employee’s hourly pay rate
• Getting the number of hours worked
• Calculating the employee’s gross pay
• Calculating overtime pay
• Calculating withholdings for taxes and benefits
• Calculating the net pay
• Printing the paycheck
Most programs perform tasks that are large enough to be broken down into several subtasks.
For this reason, programmers usually break down their programs into small manageable
pieces known as functions. A function is a group of statements that exist within a program
for the purpose of performing a specific task. Instead of writing a large program as one long

241

M05_GADD8637_05_GE_C05.indd 241 24/04/2021 12:48


Review Questions 311

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()

Figure 5-29 Output of Program 5-35

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

M05_GADD8637_05_GE_C05.indd 311 24/04/2021 12:48


312 Chapter 5  Functions

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

M05_GADD8637_05_GE_C05.indd 312 24/04/2021 12:48


Review Questions 313

10. A(n) __________ is a piece of data that is sent into a function.


a. argument
b. parameter
c. header
d. packet
11. A(n) __________ is a special variable that receives a piece of data when a function is
called.
a. argument
b. parameter
c. header
d. packet
12. A variable that is visible to every function in a program file is a __________.
a. local variable
b. universal variable
c. program-wide variable
d. global variable
13. When possible, you should avoid using __________ variables in a program.
a. local
b. global
c. reference
d. parameter
14. This is a prewritten function that is built into a programming language.
a. standard function
b. library function
c. custom function
d. cafeteria function
15. This standard library function returns a random integer within a specified range of
values.
a. random
b. randint
c. random_integer
d. uniform
16. This standard library function returns a random floating-point number in the range of
0.0 up to 1.0 (but not including 1.0).
a. random
b. randint
c. random_integer
d. uniform
17. This standard library function returns a random floating-point number within a speci-
fied range of values.
a. random
b. randint
c. random_integer
d. uniform

M05_GADD8637_05_GE_C05.indd 313 24/04/2021 12:48


314 Chapter 5  Functions

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.

M05_GADD8637_05_GE_C05.indd 314 24/04/2021 12:48


Review Questions 315

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)

M05_GADD8637_05_GE_C05.indd 315 24/04/2021 12:48


316 Chapter 5  Functions

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'.

M05_GADD8637_05_GE_C05.indd 316 24/04/2021 12:48


Programming Exercises 317

3. How Much Insurance?


Many financial experts advise that property owners should insure their homes or buildings
for at least 80 percent of the amount it would cost to replace the structure. Write a program
that asks the user to enter the replacement cost of a building, then displays the minimum
amount of insurance he or she should buy for the property.
4. Automobile Costs
Write a program that asks the user to enter the monthly costs for the following expenses
incurred from operating his or her automobile: loan payment, insurance, gas, oil, tires, and
maintenance. The program should then display the total monthly cost of these expenses,
and the total annual cost of these expenses.
5. Property Tax
A county collects property taxes on the assessment value of property, which is 60 percent of
the property’s actual value. For example, if an acre of land is valued at $10,000, its assess-
ment value is $6,000. The property tax is then 72¢ for each $100 of the assessment value.
The tax for the acre assessed at $6,000 will be $43.20. Write a program that asks for the
actual value of a piece of property and displays the assessment value and property tax.
6. Calories from Fat and Carbohydrates
A nutritionist who works for a fitness club helps members by evaluating their diets. As part
of her evaluation, she asks members for the number of fat grams and carbohydrate grams
that they consumed in a day. Then, she calculates the number of calories that result from
the fat, using the following formula:
calories from fat 5 fat grams 3 9
Next, she calculates the number of calories that result from the carbohydrates, using the
following formula:
calories from carbs 5 carb grams 3 4
The nutritionist asks you to write a program that will make these calculations.
7. Stadium Seating
There are three seating categories at a stadium. Class A seats cost $20, Class B seats cost
$15, and Class C seats cost $10. Write a program that asks how many tickets for each class
of seats were sold, then displays the amount of income generated from ticket sales.
8. Paint Job Estimator
A painting company has determined that for every 112 square feet of wall space, one gallon
of paint and eight hours of labor will be required. The company charges $35.00 per hour
for labor. Write a program that asks the user to enter the square feet of wall space to be
painted and the price of the paint per gallon. The program should display the following data:
• The number of gallons of paint required
• The hours of labor required
• The cost of the paint
• The labor charges
• The total cost of the paint job

M05_GADD8637_05_GE_C05.indd 317 24/04/2021 12:48


318 Chapter 5  Functions

9. Monthly Sales Tax


A retail company must file a monthly sales tax report listing the total sales for the month,
and the amount of state and county sales tax collected. The state sales tax rate is 5 percent
and the county sales tax rate is 2.5 percent. Write a program that asks the user to enter
the total sales for the month. From this figure, the application should calculate and display
the following:
• The amount of county sales tax
• The amount of state sales tax
• The total sales tax (county plus state)
10. Feet to Inches

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.

13. Falling Distance


When an object is falling because of gravity, the following formula can be used to deter-
mine the distance the object falls in a specific time period:
d 5 ½ gt2
The variables in the formula are as follows: d is the distance in meters, g is 9.8, and t is the
amount of time, in seconds, that the object has been falling.
Write a function named falling_distance that accepts an object’s falling time (in seconds)
as an argument. The function should return the distance, in meters, that the object has
fallen during that time interval. Write a program that calls the function in a loop that passes
the values 1 through 10 as arguments and displays the return value.

14. Kinetic Energy


In physics, an object that is in motion is said to have kinetic energy. The following formula
can be used to determine a moving object’s kinetic energy:
KE 5 ½ mv2

M05_GADD8637_05_GE_C05.indd 318 24/04/2021 12:48


Programming Exercises 319

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:

Score Letter Grade


90–100 A
80–89 B
70–79 C
60–69 D
Below 60 F

16. Odd/Even Counter


In this chapter, you saw an example of how to write an algorithm that determines
whether a number is even or odd. Write a program that generates 100 random numbers
and keeps a count of how many of those random numbers are even, and how many of
them are odd.

17. Prime Numbers


A prime number is a number that is only evenly divisible by itself and 1. For example, the
number 5 is prime because it can only be evenly divided by 1 and 5. The number 6, how-
ever, is not prime because it can be divided evenly by 1, 2, 3, and 6.
Write a Boolean function named is_prime which takes an integer as an argument and
returns true if the argument is a prime number, or false otherwise. Use the function in
a program that prompts the user to enter a number then displays a message indicating
whether the number is prime.

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.

M05_GADD8637_05_GE_C05.indd 319 24/04/2021 12:48


320 Chapter 5  Functions

18. Prime Number List


This exercise assumes that you have already written the is_prime function in Programming
Exercise 17. Write another program that displays all of the prime numbers from 1 to 100.
The program should have a loop that calls the is_prime function.

19. Loan Payments Calculator


Suppose you have taken out a loan for a certain amount of money with a fixed monthly inter-
est rate and monthly payments, and you want to determine the monthly payment amount
necessary to pay off the loan within a specific number of months. The formula is as follows:
P5 R*A
1 2 (1 1 R)2M
The terms in the formula are:
• P is the payment amount per month.
• R is the monthly interest rate, as a decimal (e.g., 2.5% 5 0.025).
• A is the amount of the loan.
• M is the number of months.
Write a program that prompts the user to enter the monthly interest rate as a percentage,
the loan amount, and the desired number of months. The program should pass these values
to a function that returns the monthly payment amount necessary. The program should
display the loan amount, interest rate, payment months, and monthly payment amount.
20. Random Number Guessing Game
Write a program that generates a random number in the range of 1 through 100, and asks
the user to guess what the number is. If the user’s guess is higher than the random number,
the program should display “Too high, try again.” If the user’s guess is lower than the
random number, the program should display “Too low, try again.” If the user guesses the
number, the application should congratulate the user and generate a new random number
so the game can start over.
Optional Enhancement: Enhance the game so it keeps count of the number of guesses that
the user makes. When the user correctly guesses the random number, the program should
display the number of guesses.
21. Rock, Paper, Scissors Game
Write a program that lets the user play the game of Rock, Paper, Scissors against the com-
puter. The program should work as follows:
1. When the program begins, a random number in the range of 1 through 3 is generated.
If the number is 1, then the computer has chosen rock. If the number is 2, then the
computer has chosen paper. If the number is 3, then the computer has chosen scissors.
(Don’t display the computer’s choice yet.)
2. The user enters his or her choice of “rock,” “paper,” or “scissors” at the keyboard.
3. The computer’s choice is displayed.
4. A winner is selected according to the following rules:
• If one player chooses rock and the other player chooses scissors, then rock wins.
(Rock smashes scissors.)
• If one player chooses scissors and the other player chooses paper, then scissors wins.
(Scissors cuts paper.)

M05_GADD8637_05_GE_C05.indd 320 24/04/2021 12:48


Programming Exercises 321

• 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.

22. Turtle Graphics: Triangle Function


Write a function named triangle that uses the turtle graphics library to draw a triangle.
The functions should take arguments for the X and Y coordinates of the triangle’s verti-
ces, and the color with which the triangle should be filled. Demonstrate the function in a
program.

23. Turtle Graphics: Modular Snowman


Write a program that uses turtle graphics to display a snowman, similar to the one shown
in Figure 5-30. In addition to a main function, the program should also have the following
functions:
• drawBase. This function should draw the base of the snowman, which is the large snow-
ball at the bottom.
• drawMidSection. This function should draw the middle snowball.
• drawArms. This function should draw the snowman’s arms.
• drawHead. This function should draw the snowman’s head, with eyes, mouth, and other
facial features you desire.
• drawHat. This function should draw the snowman’s hat.

Figure 5-30 Snowman

24. Turtle Graphics: Rectangular Pattern


In a program, write a function named drawPattern that uses the turtle graphics library
to draw the rectangular pattern shown in Figure 5-31. The drawPattern function should
accept two arguments: one that specifies the pattern’s width, and another that specifies the
pattern’s height. (The example shown in Figure 5-31 shows how the pattern would appear

M05_GADD8637_05_GE_C05.indd 321 24/04/2021 12:48


322 Chapter 5  Functions

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.

Figure 5-31 Rectangular pattern

25. Turtle Graphics: Checkerboard


Write a turtle graphics program that uses the square function presented in this chapter,
along with a loop (or loops) to draw the checkerboard pattern shown in Figure 5-32.

Figure 5-32 Checkerboard pattern

M05_GADD8637_05_GE_C05.indd 322 24/04/2021 12:48


Programming Exercises 323

26. Turtle Graphics: City Skyline


Write a turtle graphics program that draws a city skyline similar to the one shown in
Figure 5-33. The program’s overall task is to draw an outline of some city buildings against
a night sky. Modularize the program by writing functions that perform the following tasks:
• Draw the outline of buildings.
• Draw some windows on the buildings.
• Use randomly placed dots as the stars (make sure the stars appear on the sky, not on the
buildings).

Figure 5-33 City skyline

M05_GADD8637_05_GE_C05.indd 323 24/04/2021 12:48

You might also like