SlideShare a Scribd company logo
1 of 29
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("Beginningn")
myFunction()
print("Endn")
# 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 ###
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
#####################################################
########################
# 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: ") )
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
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
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 =
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”
# 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)
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
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
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.
… 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
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
8
9
1
1
2
3
4
5
6
7
8
9
2
2
4
6
8
10
12
14
16
18
3
3
6
9
12
15
18
21
24
27
4
4
8
12
16
20
24
28
32
36
5
5
10
15
20
25
30
35
40
45
6
6
12
18
24
30
36
42
48
54
7
7
14
21
28
35
42
49
56
63
8
8
16
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
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 =
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
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
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
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.
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.
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
(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
(-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
common. Why does he think this? Do you agree? Explain your
position.

More Related Content

Similar to JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptManivannan837728
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4Saranya saran
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdfpaijitk
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdfsimenehanmut
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directivesVikash Dhal
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4MKalpanaDevi
 
Function in c program
Function in c programFunction in c program
Function in c programumesh patil
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfTeshaleSiyum
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdfTeshaleSiyum
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptxvishnupriyapm4
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxKhurramKhan173
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfjanakim15
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxSangeetaBorde3
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdfpaijitk
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxrajkumar490591
 

Similar to JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx (20)

Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Functions_19_20.pdf
Functions_19_20.pdfFunctions_19_20.pdf
Functions_19_20.pdf
 
Advanced Web Technology ass.pdf
Advanced Web Technology ass.pdfAdvanced Web Technology ass.pdf
Advanced Web Technology ass.pdf
 
Preprocessor directives
Preprocessor directivesPreprocessor directives
Preprocessor directives
 
Functions and pointers_unit_4
Functions and pointers_unit_4Functions and pointers_unit_4
Functions and pointers_unit_4
 
Function in c program
Function in c programFunction in c program
Function in c program
 
Function
FunctionFunction
Function
 
Chapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdfChapter_1.__Functions_in_C++[1].pdf
Chapter_1.__Functions_in_C++[1].pdf
 
Chapter 1. Functions in C++.pdf
Chapter 1.  Functions in C++.pdfChapter 1.  Functions in C++.pdf
Chapter 1. Functions in C++.pdf
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
 
Lecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptxLecture 1_Functions in C.pptx
Lecture 1_Functions in C.pptx
 
C and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdfC and Data structure lab manual ECE (2).pdf
C and Data structure lab manual ECE (2).pdf
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
 
Functions_21_22.pdf
Functions_21_22.pdfFunctions_21_22.pdf
Functions_21_22.pdf
 
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptxIIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
IIM.Com-FIT-Unit2(14.9.2021 TO 30.9.2021).pptx
 
User Defined Functions in C Language
User Defined Functions   in  C LanguageUser Defined Functions   in  C Language
User Defined Functions in C Language
 
Lecture6
Lecture6Lecture6
Lecture6
 

More from vrickens

1000 words, 2 referencesBegin conducting research now on your .docx
1000 words, 2 referencesBegin conducting research now on your .docx1000 words, 2 referencesBegin conducting research now on your .docx
1000 words, 2 referencesBegin conducting research now on your .docxvrickens
 
1000 words only due by 5314 at 1200 estthis is a second part to.docx
1000 words only due by 5314 at 1200 estthis is a second part to.docx1000 words only due by 5314 at 1200 estthis is a second part to.docx
1000 words only due by 5314 at 1200 estthis is a second part to.docxvrickens
 
1000 words with refernceBased on the American constitution,” wh.docx
1000 words with refernceBased on the American constitution,” wh.docx1000 words with refernceBased on the American constitution,” wh.docx
1000 words with refernceBased on the American constitution,” wh.docxvrickens
 
10.1. In a t test for a single sample, the samples mean.docx
10.1. In a t test for a single sample, the samples mean.docx10.1. In a t test for a single sample, the samples mean.docx
10.1. In a t test for a single sample, the samples mean.docxvrickens
 
100 WORDS OR MOREConsider your past experiences either as a studen.docx
100 WORDS OR MOREConsider your past experiences either as a studen.docx100 WORDS OR MOREConsider your past experiences either as a studen.docx
100 WORDS OR MOREConsider your past experiences either as a studen.docxvrickens
 
1000 to 2000 words Research Title VII of the Civil Rights Act of.docx
1000 to 2000 words Research Title VII of the Civil Rights Act of.docx1000 to 2000 words Research Title VII of the Civil Rights Act of.docx
1000 to 2000 words Research Title VII of the Civil Rights Act of.docxvrickens
 
1000 word essay MlA Format.. What is our personal responsibility tow.docx
1000 word essay MlA Format.. What is our personal responsibility tow.docx1000 word essay MlA Format.. What is our personal responsibility tow.docx
1000 word essay MlA Format.. What is our personal responsibility tow.docxvrickens
 
100 wordsGoods and services that are not sold in markets.docx
100 wordsGoods and services that are not sold in markets.docx100 wordsGoods and services that are not sold in markets.docx
100 wordsGoods and services that are not sold in markets.docxvrickens
 
100 word responseChicago style citingLink to textbook httpbo.docx
100 word responseChicago style citingLink to textbook httpbo.docx100 word responseChicago style citingLink to textbook httpbo.docx
100 word responseChicago style citingLink to textbook httpbo.docxvrickens
 
100 word response to the followingBoth perspectives that we rea.docx
100 word response to the followingBoth perspectives that we rea.docx100 word response to the followingBoth perspectives that we rea.docx
100 word response to the followingBoth perspectives that we rea.docxvrickens
 
100 word response to the followingThe point that Penetito is tr.docx
100 word response to the followingThe point that Penetito is tr.docx100 word response to the followingThe point that Penetito is tr.docx
100 word response to the followingThe point that Penetito is tr.docxvrickens
 
100 word response to the folowingMust use Chicago style citing an.docx
100 word response to the folowingMust use Chicago style citing an.docx100 word response to the folowingMust use Chicago style citing an.docx
100 word response to the folowingMust use Chicago style citing an.docxvrickens
 
100 word response using textbook Getlein, Mark. Living with Art, 9t.docx
100 word response using textbook Getlein, Mark. Living with Art, 9t.docx100 word response using textbook Getlein, Mark. Living with Art, 9t.docx
100 word response using textbook Getlein, Mark. Living with Art, 9t.docxvrickens
 
100 word response to the following. Must cite properly in MLA.Un.docx
100 word response to the following. Must cite properly in MLA.Un.docx100 word response to the following. Must cite properly in MLA.Un.docx
100 word response to the following. Must cite properly in MLA.Un.docxvrickens
 
100 original, rubric, word count and required readings must be incl.docx
100 original, rubric, word count and required readings must be incl.docx100 original, rubric, word count and required readings must be incl.docx
100 original, rubric, word count and required readings must be incl.docxvrickens
 
100 or more wordsFor this Discussion imagine that you are speaki.docx
100 or more wordsFor this Discussion imagine that you are speaki.docx100 or more wordsFor this Discussion imagine that you are speaki.docx
100 or more wordsFor this Discussion imagine that you are speaki.docxvrickens
 
10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx
10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx
10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docxvrickens
 
10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx
10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx
10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docxvrickens
 
10-12 page paer onDiscuss the advantages and problems with trailer.docx
10-12 page paer onDiscuss the advantages and problems with trailer.docx10-12 page paer onDiscuss the advantages and problems with trailer.docx
10-12 page paer onDiscuss the advantages and problems with trailer.docxvrickens
 
10. Assume that you are responsible for decontaminating materials in.docx
10. Assume that you are responsible for decontaminating materials in.docx10. Assume that you are responsible for decontaminating materials in.docx
10. Assume that you are responsible for decontaminating materials in.docxvrickens
 

More from vrickens (20)

1000 words, 2 referencesBegin conducting research now on your .docx
1000 words, 2 referencesBegin conducting research now on your .docx1000 words, 2 referencesBegin conducting research now on your .docx
1000 words, 2 referencesBegin conducting research now on your .docx
 
1000 words only due by 5314 at 1200 estthis is a second part to.docx
1000 words only due by 5314 at 1200 estthis is a second part to.docx1000 words only due by 5314 at 1200 estthis is a second part to.docx
1000 words only due by 5314 at 1200 estthis is a second part to.docx
 
1000 words with refernceBased on the American constitution,” wh.docx
1000 words with refernceBased on the American constitution,” wh.docx1000 words with refernceBased on the American constitution,” wh.docx
1000 words with refernceBased on the American constitution,” wh.docx
 
10.1. In a t test for a single sample, the samples mean.docx
10.1. In a t test for a single sample, the samples mean.docx10.1. In a t test for a single sample, the samples mean.docx
10.1. In a t test for a single sample, the samples mean.docx
 
100 WORDS OR MOREConsider your past experiences either as a studen.docx
100 WORDS OR MOREConsider your past experiences either as a studen.docx100 WORDS OR MOREConsider your past experiences either as a studen.docx
100 WORDS OR MOREConsider your past experiences either as a studen.docx
 
1000 to 2000 words Research Title VII of the Civil Rights Act of.docx
1000 to 2000 words Research Title VII of the Civil Rights Act of.docx1000 to 2000 words Research Title VII of the Civil Rights Act of.docx
1000 to 2000 words Research Title VII of the Civil Rights Act of.docx
 
1000 word essay MlA Format.. What is our personal responsibility tow.docx
1000 word essay MlA Format.. What is our personal responsibility tow.docx1000 word essay MlA Format.. What is our personal responsibility tow.docx
1000 word essay MlA Format.. What is our personal responsibility tow.docx
 
100 wordsGoods and services that are not sold in markets.docx
100 wordsGoods and services that are not sold in markets.docx100 wordsGoods and services that are not sold in markets.docx
100 wordsGoods and services that are not sold in markets.docx
 
100 word responseChicago style citingLink to textbook httpbo.docx
100 word responseChicago style citingLink to textbook httpbo.docx100 word responseChicago style citingLink to textbook httpbo.docx
100 word responseChicago style citingLink to textbook httpbo.docx
 
100 word response to the followingBoth perspectives that we rea.docx
100 word response to the followingBoth perspectives that we rea.docx100 word response to the followingBoth perspectives that we rea.docx
100 word response to the followingBoth perspectives that we rea.docx
 
100 word response to the followingThe point that Penetito is tr.docx
100 word response to the followingThe point that Penetito is tr.docx100 word response to the followingThe point that Penetito is tr.docx
100 word response to the followingThe point that Penetito is tr.docx
 
100 word response to the folowingMust use Chicago style citing an.docx
100 word response to the folowingMust use Chicago style citing an.docx100 word response to the folowingMust use Chicago style citing an.docx
100 word response to the folowingMust use Chicago style citing an.docx
 
100 word response using textbook Getlein, Mark. Living with Art, 9t.docx
100 word response using textbook Getlein, Mark. Living with Art, 9t.docx100 word response using textbook Getlein, Mark. Living with Art, 9t.docx
100 word response using textbook Getlein, Mark. Living with Art, 9t.docx
 
100 word response to the following. Must cite properly in MLA.Un.docx
100 word response to the following. Must cite properly in MLA.Un.docx100 word response to the following. Must cite properly in MLA.Un.docx
100 word response to the following. Must cite properly in MLA.Un.docx
 
100 original, rubric, word count and required readings must be incl.docx
100 original, rubric, word count and required readings must be incl.docx100 original, rubric, word count and required readings must be incl.docx
100 original, rubric, word count and required readings must be incl.docx
 
100 or more wordsFor this Discussion imagine that you are speaki.docx
100 or more wordsFor this Discussion imagine that you are speaki.docx100 or more wordsFor this Discussion imagine that you are speaki.docx
100 or more wordsFor this Discussion imagine that you are speaki.docx
 
10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx
10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx
10. (TCOs 1 and 10) Apple, Inc. a cash basis S corporation in Or.docx
 
10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx
10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx
10-12 slides with Notes APA Style ReferecesThe prosecutor is getti.docx
 
10-12 page paer onDiscuss the advantages and problems with trailer.docx
10-12 page paer onDiscuss the advantages and problems with trailer.docx10-12 page paer onDiscuss the advantages and problems with trailer.docx
10-12 page paer onDiscuss the advantages and problems with trailer.docx
 
10. Assume that you are responsible for decontaminating materials in.docx
10. Assume that you are responsible for decontaminating materials in.docx10. Assume that you are responsible for decontaminating materials in.docx
10. Assume that you are responsible for decontaminating materials in.docx
 

Recently uploaded

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfakmcokerachita
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 

Recently uploaded (20)

How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Class 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdfClass 11 Legal Studies Ch-1 Concept of State .pdf
Class 11 Legal Studies Ch-1 Concept of State .pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 

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.