JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to Computer Science with Java, Python and C++, written by Charles Herbert. It is available free of charge for students in Computer Science courses at Community College of Philadelphia during the Fall 2019 semester. It may not be reproduced or distributed for any other purposes without proper prior permission.
Please report any typos, other errors, or suggestions for improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous Python script. We have used functions from other python modules, such as the square root method from the math class math.sqrt(n). Now we will begin to create our own functions of our own.
A Python function is a block of code that can be used to perform a specific task within a larger computer program. It can be called as needed from other Python software. Most programming languages have similar features, such as methods in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a function definition. A Python function definition is a software unit with a header and a block of Python statements. The header starts with the keyword def followed by the name of the function, then a set parenthesis with any parameters for the function. A colon is used after the parentheses to indicate a block of code follows, just as with the if and while statements. The block of code to be included within the function is indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function MyFunction.\n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginning\n")
myFunction()
print("End\n")
# end main program
Functions can used for code that will be repeated within a program, or for modular development, in which long programs are broken into parts and the parts are developed independently. The parts can be developed as Python functions, then integrated to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the function. Function parameters are variables listed in parentheses foll ...
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
1. JLK Chapter 5 – Methods and ModularityDRAFT January 2015
Edition pg. 25
An Introduction to
Computer Science with Java, Python and C++
Community College of Philadelphia edition
Copyright 2017 by C.W. Herbert, all rights reserved.
Last edited October 8, 28, 2019 by C. W. Herbert
This document is a draft of a chapter from An Introduction to
Computer Science with Java, Python and C++, written by
Charles Herbert. It is available free of charge for students in
Computer Science courses at Community College of
Philadelphia during the Fall 2019 semester. It may not be
reproduced or distributed for any other purposes without proper
prior permission.
Please report any typos, other errors, or suggestions for
improving the text to [email protected]
Chapter 5 – Python Functions and Modular Programming
Contents
Lesson 5.1User Created Functions in Python2
Python Function Parameters2
Value returning functions3
Example – Methods and Parameter Passing5
9
Lesson 5.2Top-Down Design and Modular Development10
Chapter Exercises13
User Created Functions in Python
So far we have only created software with one continuous
Python script. We have used functions from other python
modules, such as the square root method from the math class
math.sqrt(n). Now we will begin to create our own functions of
our own.
A Python function is a block of code that can be used to
2. perform a specific task within a larger computer program. It
can be called as needed from other Python software. Most
programming languages have similar features, such as methods
in Java or subroutines in system software.
The code for user-defined functions in Python is contained in a
function definition. A Python function definition is a software
unit with a header and a block of Python statements. The header
starts with the keyword def followed by the name of the
function, then a set parenthesis with any parameters for the
function. A colon is used after the parentheses to indicate a
block of code follows, just as with the if and while statements.
The block of code to be included within the function is
indented.
Here is an example of a Python function:
# firstFunction.py
# first demonstration of the use of a function for CSCI 111
# last edited 10/08/2o19 by C. Herbert
function
definition
def myFunction():
print ( "This line being printed by the function
MyFunction.n")
# end myFunction()
### main program ###
function used by the main part of the script
print("Beginningn")
myFunction()
print("Endn")
3. # end main program
Functions can used for code that will be repeated within a
program, or for modular development, in which long programs
are broken into parts and the parts are developed independently.
The parts can be developed as Python functions, then integrated
to work together by being called from other software.
Python Function Parameters
Data can be passed to a Python function as a parameter of the
function. Function parameters are variables listed in
parentheses following the name of the function in the function
definition. Actual parameters are corresponding values included
in parentheses when the function is called. The values are used
to initialize the variables.
Here is an example of a Python function with a single
parameter:
# messageFunction.py
formal parameter
used as a local variable
# demonstrating the use of a function parameter
# last edited 10/08/2o19 by C. Herbert
def printMessage(msg):
print ( "The msessage is:", msg, "n")
# end printMessage()
actual parameter
# main program ###
4. print("Beginningn")
printMessage("Hello, world!")
print("Endn")
# end main program
The value of the actual parameter, the string "Hello, world!", is
passed to the formal parameter, msg, which is used as a local
variable within the function. Here is the output from the
program:
Value returning functions
A Python function can return a value using the return statement,
followed by the value to be returned or a variable whose value
is to be returned. The call to the function should be used in the
main program where the returned value is to be used.
The returned value can be used in a Python function just as any
other value can be used – in a print statement, an assignment
statement, etc. A value retuning function must be called from a
place where the returned value can be used. It cannot be called
by itself on a single line, as a function that does not return a
value can be.
The next page is an example of a payroll program with a method
to calculate overtime:
# pay.py
# sample payroll program with an overtime function returning a
value
# last edited 10/08/2019 by C. Herbert
#####################################################
########################
5. # The overtime function calculates the total overtime pay
following the time
# and a half for overtime rule. The result is to be added to the
regular pay
# for 40 hours.
# function parameters:
# float hours -- hours worked this week – usually close to 40.0
# float rate -- employee's pay rate a decimal values usually less
than 100
# The function returns the total overtime pay for hours above
40.
def getOverTime(hours, rate):
overtimeHours = 0,0 # hours worked beyond 40
overtimePay = 0.0 # pay for overtime hours
# calculate overtime hours and pay
overtimeHours = hours - 40.0
overtimePay = overtimeHours *rate * 1.5
This function returns the value
of the variable overtime
return overtimePay
# end overtime ()
#####################################################
########################
# main program
# get the hours and rate form the user a floating point values
hours = float( input("enter the number of hours worked: ") )
6. rate = float( input("enter the hourly pay rate: ") )
print()
# calculate pay with overtime if there is any -- if hours > 40
# else calculate regular pay
call to the overtime function in an assignment statement. The
returned value will be used here.
if (hours > 40.0):
regular = 40.0 * rate
overtime = getOverTime(hours, rate)
else:
regular = hours * rate
overtime = 0.0;
# print results
print("hours: ", hours,)
print("rate: ", rate)
print()
print("regular pay: ", regular)
print("overtime pay: ", overtime)
Example – Methods and Parameter Passing
In this example we will develop a modular solution for a
problem similar to a previous assignment.
We wish to input the x and y coordinates for two points in the
Cartesian plane, and find the distance between the two points,
then print a report with the the distance between the two points
and the quadrant that each point is in.
The distance between two points whose coordinates are (x1,y1)
and (x2, y2) is where Δx is the difference between the two x
coordinates (x1- x2)and Δy is the difference between the y
7. coordinates (y1- y2). The hypotenuse function can be used
here. It will give us the square root of the sum of two numbers
squared, so hyp(,) will give us the distance between the two
points.
The example on the right shows us that the quadrants of a
Cartesian plane are numbered I through IV, with the following
properties:
· If both x and y are non-negative,
the point is in Quadrant I.
· If x is negative and y is non-negative,
the point is in Quadrant II
· If x and y are both negative,
the point is in Quadrant III.
· If x is non-negative and y is negative,
the point is in Quadrant IV.
two points in a Cartesian plane
Once we understand the specifications, we can make an outline
of what our software should do:
1. get the coordinates of two points: (x1, y1) and (x2, y2)
2. calculate the distance between the two points:
· deltaX =x1-x2; deltaY = y1-y2;
· dist = math.hypot(deltaX, deltaY);
3. determine which quadrant (x1, y1) is in:
· If (x >=0) && y>=0) Quadrant I
· If (x <0) && y>=0) Quadrant II
· If (x <0) && y<0) Quadrant III
· If (x >=0) && y<0) Quadrant IV
4. determine which quadrant (x2, y2) is in:
· If (x >=0) && y>=0) Quadrant I
· If (x <0) && y>=0) Quadrant II
· If (x <0) && y<0) Quadrant III
· If (x >=0) && y<0) Quadrant IV
8. 5. print results
We can create two Python functions to use as part of the
solution to this problem:
· One function will accept the x and y coordinates of two points
as parameters and then calculate and return the distance
between the two points. This is part 2 in our outline above.
· Another function can accept the x and y points for one point
and return a string reporting stating the quadrant that the point
is in. This function can be used for parts 3 and 4 in our outline
above. This is a good example of reusable code – a function that
can be used twice, but each time with different values.
Part 1 of our outline might seem like a good place for a method
– we get four numbers from the user, each in the same manner.
However, remember that methods can only return one value, so
we really don’t gain much by making this a separate method. It
is a judgment call and a matter of programming style – it could
be done with four calls to one method, but in this case we will
use four input statements in the main method.
Here in the design of our software, with descriptions of the
functions:
define a function -- findDistance(x1, y1, x2 y2):
· Calculate deltaX -- x1-x2
· Calculate deltaY -- y1-y2
· Calculate distance using the hypotenuse function
math.hypot(deltaX, deltaY)
· return distance
define a function -- findQuadrant(x, y)
· if (x >=0) && (Y>=0) quad = “quaduadrant I”
· else if if (x <0) && (Y>=0) quad =“quaduadrant II”
· else if (x <0) && (Y<0) quad =“quaduadrant III”
· else (x >=0) && (Y<0) quad =“quaduadrant IV”
· return quad
The main program
· Get four input values – x1, y1, x2, y2
· Call the function to calculate distance -- distance =
9. findDistance(x1, y1, x2, y2)
· Call method to determine quadrant of point 1 -- quadPt1 =
findQuadrant(x1, y1)
· Call method to determine quadrant of point 2 -- quadPt1 =
findQuadrant(x1, y1)
· Print the results
The next step is to copy our outline into a Python program and
start to turn it into a program. Don't forget the identifying
comments at the top of the file. You can copy and paste these
from an older program, then edit them. The python file with the
comments is shown on the next page.
# twoPoints.py
# a sample program to calculate the the distance between two
points
# and which quadrant each point is in
# last edited Oct 8, 2019 by C. Herbert
# define a function to find the distance between two points
# -- findDistance(x1, y1, x2 y2):
# calculate deltaX -- x1-x2
# Calculate deltaY -- y1-y2
# Calculate the distance between the two points using
math.hypot()
#return distance
# end function
# define a function to determine which quadrant a point s in --
findQuadrant(x, y)
# if (x >=0) && (Y>=0) quad = “quaduadrant I”
# else if if (x <0) && (Y>=0) quad =“quaduadrant II”
# else if (x <0) && (Y<0) quad =“quaduadrant III”
# else (x >=0) && (Y<0) quad =“quaduadrant IV”
10. # return quad
# end function
# the main program
# Get four input values – x1, y1, x2, y2
# call the function to calculate distance
# call method to determine quadrant of point 1
# call method to determine quadrant of point 2
# Print the results
# end main
The last step in creating the program is to create the
instructions in the program to do what the comments tell us the
program needs to do, then test and debug the program. In some
cases, such as the if…else structure, parts of the comment can
be changed directly into Python code.
Here is the resulting program:
# twoPoints.py
# a sample program to calculate the the distance between two
points
# and which quadrant each point is in
# last edited Oct 8, 2019 by C. Herbert
import math
#####################################################
####################
# function to find the distance between two points
def findDistance(x1, y1, x2, y2):
# calculate deltaX and deltY
deltaX = x1-x2
deltaY = y1-y2
# Calculate the distance between the two points
distance = math.hypot(deltaX, deltaY)
11. return distance
# end findDistance()
(continued on next page)
(twoPoints.py – continued from last page)
#####################################################
####################
# function to determine which quadrant a point s in -
def findQuadrant(x, y):
if ( (x >=0) and (y>=0) ):
quad = "quadrant I"
elif ( (x <0) and (y>=0) ):
quad ="quadrant II"
elif ( (x <0) and (y<0) ):
quad ="quadrant III"
else:
quad ="quadrant IV"
return quad
# end findDistance()
#####################################################
####################
# the main program
# Get four input values – x1, y1, x2, y2
x1 = int ( input("Enter the X-coordinate of point 1: ") )
y1 = int ( input("Enter the Y-coordinate of point 1: ") )
x2 = int ( input("Enter the X-coordinate of point 2: ") )
y2 = int ( input("Enter the Y-coordinate of point 1: ") )
# call the function to calculate distance
dist = findDistance(x1, y1, x2, y2)
# call functions to determine quadrant of points 1 and 2
12. quadPt1 = findQuadrant(x1, y1)
quadPt2 = findQuadrant(x2, y2)
# Print the results
print()
print("the two points are:")
print("t(" , x1, "," ,y1, ")" )
print("t(" , x2, "," ,y2, ")" )
print()
print("The distance between the points is:" , dist)
print()
print("The first point is in" , quadPt1)
print("The second point is in" , quadPt2)
# end main
The files Two Points Outline.txt,twoPointsNotes.py and
twoPoints.py are included with the files for the Chapter.
a copy of a sample run of the finished program is included on
the next page.
Here is sample output from the program:
Top-Down Design and Modular Development
It’s hard to solve big problems.
It’s easier to solve small problems than it is to solve big ones.
Computer programmers use a divide and conquer approach to
problem solving:
· a problem is broken into parts
· those parts are solved individually
· the smaller solutions are assembled into a big solution
This process is a combination of techniques known as top-down
design and modular development.
Top-down design is the process of designing a solution to a
13. problem by systematically breaking a problem into smaller,
more manageable parts.
First, start with a clear statement of the problem or concept – a
single big idea. Next, break it down into several parts. If any of
those parts can be further broken down, then the process
continues until you have a collection of parts that each do one
thing.
The final design might look something like this organizational
chart, showing the overall structure of separate units that form a
single complex entity.
Figure 9 – an organizational chart showing units that form a
single complex entity
An organizational chart is like an upside down tree, with nodes
representing each process. The leaf nodes are those at the end
of each branch of the tree. The leaf nodes represent modules
that need to be developed and then recombined to create the
overall solution to the original problem.
Figure 10 the leaf nodes of an organizational chart
Top-down design leads to modulardevelopment.Modular
developmentis the process of developing software modules
individually, then combining the modules to form a solution to
an overall problem.
Modular development facilitates production of computer
software because it:
… makes a large project more manageable.
Smaller and less complex tasks are easier to understand than
larger ones and are less demanding of resources.
14. … is faster for large projects.
Different people can work on different modules, and then put
their work together. This means that different modules can be
developed at the same time, which speeds up the overall project.
… leads to a higher quality product.
Programmers with knowledge and skills in a specific area, such
as graphics, accounting, or data communications, can be
assigned to the parts of the project that require those skills.
…makes it easier to find and correct errors.
Often, the hardest part of correcting an error in computer
software is finding out exactly what is causing the error.
Modular development makes it easier to isolate the part of the
software that is causing trouble.
… increases the reusability of solutions.
Solution
s to smaller problems are more likely to be useful elsewhere
than solutions to bigger problems. They are more likely to be
reusable code. Reusable code is code that can be written once,
then called upon again in similar situations. It makes
programming easier because you only need to develop the
solution to a problem once; then you can call up that code
whenever you need it. Modules developed as part of one
project, can be reused later as parts of other projects, modified
if necessary to fit new situations. Over time, libraries of
software modules for different tasks can be created. Libraries of
objects can be created using object-oriented programming
15. languages.
Most computer systems are filled with layers of short
programming modules that are constantly reused in different
situations. Our challenge as programmers is to decide what the
modules should be. Each module should carry out one clearly
defined process. It should be easy to understand what the
module does. Each module should form a single complete
process that makes sense all by itself.
Top-down development is used to figure out what the modules
are needed in a software development project and how they
should be organized. Modular development involves building
those modules as separate methods, then combining them to
form a complete software solution for the project.
Chapter Exercises
1. Multiplication Table
A set of nested for loops can be used to print a multiplication
table using formatted printstatements.
1
2
3
4
5
6
7
19. 24
32
40
48
56
64
72
9
9
18
27
36
45
54
63
72
81
Write a program to print such a multiplication table, using a
function to print each row, which is invoked from the function
that prints the overall multiplication table.
2. Celsius to Fahrenheit Table
Write a program to print a Celsius to Fahrenheit conversion
20. table that invokes a function to calculate Fahrenheit temperature
using formula is F = ( C) + 32.0. The main program should
have a loop to print the table, calling the conversion function
from within the loop.
The table should include integer Celsius degrees from 0 to 40.
You program does not need to use integers, but the table should
display the Celsius temperature, then the Fahrenheit accurate to
one-tenth of a degree. The first few entries from the table are
shown below:
Celsius
Fahrenheit
0
32.0
1
33.8
2
35.6
3
37.4
3. We wish to write a modular program that can be used to
calculate monthly payments on a car loan. The formula is:
payment =
21. The program will be use two functions – the main program, a
monthly payment function, and an output function.
The main program should:
1. ask the user for
- the loan amount
- the annual interest rate ( as a decimal, 7.5% is 0.075 )
- the number of months
2. call a function to calculate and return the monthly payment
(Note: The formula uses monthly rate. Annual rate is input.
monthly rate = annual rate/12)
3. call a function to print a loan statement showing the amount
borrowed, the annual interest rate, the number of months, and
the monthly payment
4. International Gymnastics Scoring
We wish to write a program to quickly calculate gymnastics
scores for an international competition. Six judges are judging
the competition, numbered 1 through 6 for anonymity. The
program should have a loop that:
1. calls a function asking for the score from a single judge. The
function should print the judge number and score for that judge
and return the judge's score
2. adds the returned score to a total score.
After the loop is done, your program should call a function that
22. calculates and displays the average score.
Scores are in the range 0 to 10 with one decimal place, such as
8.5. Don't forget to initialize the total score to zero before the
loop begins.
Here is a sample of the output:
Score for Judge 1: 8.5
Score for Judge 2: 8.7
Score for Judge 3: 8.4
Score for Judge 4: 9.1
Score for Judge 5: 8.9
Score for Judge 6: 9.0
The average score is: 8.77
5. Test for Divisibility
If the remainder from dividing A by B is zero, then A is a
multiple of B ( A is evenly divisible by B ).
For example, the remainder from dividing 6, 9, or 12 by 3 is 0,
which means 6, 9, and 12 are all multiples of 3.
Create a function to see if one number is a multiple of another.
Write a program with a loop to print the numbers from 1 to 25,
and within the loop, invoke the function three times to see if the
number is a multiple of 2, if the number is a multiple of 3, and
if the number is a multiple of 5. You should have one multiple
23. function with two inputs – the number being tested and the
number we are dividing by. The function should print a
message if the number is a multiple of the value which it is
testing.
Here is a sample of part of the output:
1
2multiple of 2
3multiple of 3
4multiple of 2
5multiple of 5
6multiple of 2multiple of 3
7
8multiple of 2
9multiple of 3
10multiple of 2multiple of 5
6. Estimate of a Definite Integral
Write the program to estimate a definite integral with
rectangles, with a loop that calls a function to calculate the
height and area of each rectangle.
A loop in a computer program can be used to approximate the
value of a definite integral. We can break the integral into
rectangles, find the area of each rectangle then add the areas
together to get the total area, as shown in the accompanying
diagram. In practice, we could make the width small enough to
24. achieved the desired accuracy in estimating the area under the
curve.
As the width of the rectangles gets progressively smaller, their
total area gets closer to the total area under the curve. This is an
old function that predates Calculus. Both Leibnitz and Newton
used this function, eventually developing calculus from the
concept of infinitesimals, which, in the case of our rectangles,
would amount to asking, what would the total area be if the
number of rectangles approaches infinity and the width
approaches zero?
This was tedious by hand, but we now have computers. We can
set the width of the rectangle. The height of the rectangle is the
y value at point x. So for example, if we need to solve:
The starting point is -3, the ending point is +3, and the height of
the rectangle at each value of x in between the two is ; Y at
each x is the is the height of the rectangle at that x. We can use
a width of 0.001, and write a loop like this:
width = .1
x = -3.0
while (x <= +3 ) # x is -3.00, then -2.9, then -2.8, etc.
25. y = // the height is the y value at each x
area = y * width// the width is the increment, in this case 0.1
totalArea = totalArea + area
x += width
# end whuile()
In this version of the program, the statements in the box above
should be in a separate function, invoked from within the loop.
When the loop is finished, totalArea is the total area of the
rectangles, which is an approximation of the area under the
curve.
7. Supermarket Checkout
Design a program for a terminal in a checkout line at a
supermarket. What are the tasks that are included as part of
checking out at a register? We must consider things like the cost
of each item, weighing produce and looking up produce codes,
the total cost of the order, bonus card discounts, and sales tax
on taxable items only. You do not need to write the program,
but you should design the functions using top down
development and modular design. Submit a description of the
functions needed for the program, a brief description of what
each function does, and a description of how the functions are
related to one another in terms of parameter passing and return
types.
26. 8. We wish to write a program to draw the scene below. We can
create functions to draw primitive shapes, as follows:
circle() takes x and y coordinates of center point, the radius,
and the color
triangle() takes x and y coordinates of each of three endpoints
and the color
rectangle() takes x and y coordinates of each of four corner
points and the color
Create a modular design for software to draw the scene using
the functions above. The software should be layered. For
example, a house() function should use the primitive graphics
functions to draw the house.
Your design document should list and briefly describe each
function, including and what it does, parameters, and any
functions the function calls. Your design should include the
main program.
Y axis
X axis
(4,4)
Δy = 8
27. (0,0)
Quadrant IQuadrant II
Quadrant IIIQuadrant IV
(-2,-4)
Δx = 6
Y axis
X axis
(4,4)
Δx = 6
Δy = 8
(0,0)
Quadrant I
Quadrant II
Quadrant III
Quadrant IV
28. (-2,-4)
y = 9-x
2
area under the curve
estimated by rectangles
y = 9-x2
area under the curve
estimated by rectangles
1 According to the Socratic view of morality summarized by
Frankena, is a person brought up by immoral parents in a
corrupt society capable of making correct moral judgments?
Why or why not? Do you agree?
2 On some moral matters there is longstanding and widespread
agreement. For example, all agree that killing innocent children
is wrong. In such cases, is it still important that we supply
reasons to support our moral judgments? Is it permissible, in
some cases, to simply accept a unanimously agreed-upon moral
judgment?
3 Cahn argues that God’s existence would not matter morally.
How does he defend this assertion? Do you find his argument
compelling? Why or why not?
4 Rachels argues that all cultures must have some values in
29. common. Why does he think this? Do you agree? Explain your
position.