Title arial bold 28pt
Dr. Adrian Euler
adrian. .uk
Lecture 3 & 4
Program Design & User-Defined Functions
SMM283
Introduction to Python
www.cass.city.ac.uk
1
“… the more slow and dim-witted your pupil, the more you have to break things down into more and more simple ideas. And that’s really the essence of programming.”
From Dirk Gently’s Holistic Detective Agency
www.cass.city.ac.uk
PROGRAM DESIGN
Modularization of a program
www.cass.city.ac.uk
Top-Down Design
To make a complicated problem more understandable
Divide it into smaller, less complex sub-problems.
Called stepwise refinement
Top-down design and structured programming
Techniques to enhance programming productivity
www.cass.city.ac.uk
Top-Down Design
Criteria:
Design should be easily readable and emphasize small module size.
Tasks proceed from general to specific as you read down the chart.
Subtasks should be single-minded.
Subtasks should be independent of each other.
www.cass.city.ac.uk
Structured Programming
Meets modern standards of program design
Use top-down design
Use only the three types of logical structures:
Sequences – Statements executed one after the other
Decisions – blocks of code executed based on test of some
condition
Loops – blocks of coded executed repeatedly based on some condition
www.cass.city.ac.uk
Advantages of Structured Programming
Easy to write
Easy to debug
Easy to understand
Easy to change
www.cass.city.ac.uk
Modularization of a program
The modularization process is the process of dividing a problem into subtasks, or modules.
Modules are self contained entities of code that perform some specific function or task.
Activities to to be performed should map logically to a specific module.
Activities should be grouped together to form manageable tasks or functions which will eventually form programming functions.
Functions individually should be made up of a number of activities, all of which should contribute to the performance of a single task.
Note: Term module is a general term(applicable as a concept to all programming languages), and not to be confused with the term module (library) in Python.
www.cass.city.ac.uk
8
Modularization of a program
A module should be large enough to perform its task, and must include the operations that contribute to the performance of the task.
Modules should have:
a single entry; could be more than one piece of data or information.
a single exit; could be more than one piece of data returned through variable address handlings.
a top to bottom sequence of instructions.
Module’s name should describe the work to be done as a single specific function.
Name convention: use a verb followed by one or more words related to the specific task the module is supposed to perform.
www.cass.city.ac.uk
9
Modularization of a program
Each program must have:
a mainline function(the main function as it appears in most of high level programming languages
a clear interface must exist between the mainline function and the rest of the user defined functions.
a mainline routine must provide the master control that ties all the modules together and coordinates their activity (i.e. define one .
www.cass.city.ac.uk
Modularization of a program
The program’s mainline should:
show the main processing functions, and the order in which they are to be performed
it should also show the flow of information or data and the major control structures.
must be easy to read, be of manageable length and show sound logic structure.
Note: Generally you should be able(this comes with experience) to read a pseudocode/real code mainline/main and see exactly what is been done in the program.
www.cass.city.ac.uk
Communication between modules
When designing pseudo-code or real-code solutions to a problem, consider
breaking up of the problem into modules
the flow of information between the modules.
The fewer and simpler the communications between modules, the easier it is to understand and maintain one module without reference to other modules.
This flow of information between modules is properly called inter-modal communication and it is accomplished by the scope of the variable
local, global, parameter variables.
www.cass.city.ac.uk
Communication between modules
The scope of a variable is the portion of the program in which the variable has been defined and to which it can be referred.
If a list is created of all the modules in which a variable can be referenced, then the that list defines the scope of that particular variable.
Variables may have
a local scope, where the scope of the variable is simply that particular module in which the variable is defined or
a global scope, where the scope of the variable is the whole program.
www.cass.city.ac.uk
Module Cohesion
Module cohesion: a measure of the internal strength of a module i.e. how closely elements or statements of a module are associated with each other.
The more closely the elements of a module are associated, the higher the cohesion of the module.
Modules with high cohesion are considered good modules, because of their internal strength.
www.cass.city.ac.uk
Module Cohesion
The term function in programming refers to this type of module
www.cass.city.ac.uk
Module Cohesion
Coincidental Cohesion:
Elements or statements are collected or packed within a module simply because they happen to fall together.
There is no meaningful relationship between elements or statements
difficult to assign a specific task or function to the module.
www.cass.city.ac.uk
Module Cohesion
Logical Cohesion:
Elements or statements fall into some general category because they all do the same kind of thing.
It follows logic grouping of items into modules of this kind
Logical cohesive modules are usually made up of smaller, independent sections
could exist independently and as separate modules
www.cass.city.ac.uk
Module Cohesion
Temporal Cohesion:
Elements of a module are grouped together because they are related by time.
Typical modules of this kind are initialization and finalization modules.
elements are placed together because they perform certain “housekeeping” functions at the beginning or end of a program
www.cass.city.ac.uk
Module Cohesion
Procedural cohesion:
Elements of a module are related because they operate according to a particular procedure.
Elements are executed in a particular sequence so that the objectives of the program are achieved.
A typical example of a procedural cohesive module is the mainline(main) function.
Elements of the main are grouped together because of a particular procedural order.
The weakness of procedurally cohesive modules
they cut across functional boundaries.
www.cass.city.ac.uk
Module Cohesion
Communicational cohesion:
Elements of a module are grouped together because they all operate on the same (central) piece of data.
commonly found in business applications
i.e. a module may contain all the validations of the fields of a record, or all the processing required to assemble a report line for printing.
The weakness of this kind of module:
a combination of processing for a particular piece of data is performed, rather than separate and independent processes.
www.cass.city.ac.uk
Module Cohesion
Sequential cohesion:
module contains elements that depend on the processing of previous elements.
It might contain elements in which the output data from one element serves as input data to the next.
can be seen as a series of sequential steps performing successive transformation of data.
The weakness:
Module may contain multiple function or fragments of functions.
www.cass.city.ac.uk
Module Cohesion
Functional Cohesive:
All the elements of a module contribute to the performance of a single task.
The module can be easily named by a single verb followed by one or more(not two many!) words.
Mathematically oriented modules are good examples of functional cohesion
the elements making up the module form an integral part of the calculation.
Note: There will be situation though that the circumstances do not permit for a complete functional cohesive module, in which case one can settle for a module with a weaker cohesion.
www.cass.city.ac.uk
22
Module coupling
Module coupling is a measure of the extend of information interchange between modules.
Tight coupling implies large dependence on the structure of one module by another.
Many paths along which errors can extend into other parts of the program.
Loose coupling, means that modules have more independence and are easier to maintain.
www.cass.city.ac.uk
Module coupling
www.cass.city.ac.uk
Module coupling
Common coupling:
Common coupling occurs when modules reference the same global data structure(a data structure is a collection of related data items i.e. a list for instance.
When modules experience common coupling, a global data structure is shared by the modules.
Data can be accessed and modified by any module in the program.
Makes the program difficult to read
www.cass.city.ac.uk
Module coupling
External coupling
External coupling occurs when two or more modules access the same global data variable.
It is similar to common coupling except that the global variable is an elementary data item, rather than a data structure.
Because the global data has a simpler structure, external coupling is considered to be looser than common coupling.
www.cass.city.ac.uk
Module coupling
Control coupling:
Control coupling occurs when a module passes another module a control variable that is intended to control the other module’s logic.
Control variables are often referred as program flags, or switches; passed between modules in the form of parameters.
The weakness:
the passing of control field between modules implies that one module is aware of the internal logic of the other
www.cass.city.ac.uk
Module coupling
Stamp coupling:
Stamp coupling occurs when one module passes a non global data structure to another module.
The non global data structure is passed in the form of a parameter.
Stamp coupled modules demonstrate loose coupling and offer good module design quality.
The only relationship between the two modules is the passing of the data structure between them.
www.cass.city.ac.uk
Module coupling
Data coupling:
Data coupling occurs when a module passes a non-global data variable to another module.
Similar to stamp coupling except that the non-global data variable is an elementary data item, not a data structure.
Modules that are data coupled demonstrate the loosest coupling between the modules:
the only relationship between the two modules is the passing of one or more data items between them
www.cass.city.ac.uk
USER-DEFINED FUNCTIONS
PART I
www.cass.city.ac.uk
Built-in Functions
Like miniature programs
Receive input
Process the input
Have output
Table 1 Some Python built-in functions.
www.cass.city.ac.uk
Built-in Functions
Output of functions is a single value
Function is said to return its output
Items inside parentheses called arguments
Examples:
www.cass.city.ac.uk
User-defined Functions
Defined by statements of the form
par1, par2 are variables (called parameters)
Expression evaluates to a literal of any type
Header must end with colon
Each statement in block indented same
parameters
Evaluates to a value
Delimits header
indented
www.cass.city.ac.uk
User-defined Functions
Passing parameters
We consider here pass by position
Arguments in calling statement matched to the parameters in function header based on order
Parameters and return statements optional in function definitions
Function names should describe the role performed
www.cass.city.ac.uk
FUNCTIONS HAVING ONE PARAMETER
Example: Header of the user-defined factorial and inputInt functions
www.cass.city.ac.uk
Functions Having One Parameter
Example: Program uses the function factorial and inputInt
Call functions
www.cass.city.ac.uk
Functions Having One Parameter
Example: Program uses the functions firstName and lastName
www.cass.city.ac.uk
37
Passing a Value to a Function
If the argument in a function call is a variable
Object pointed to by the argument variable
(not the argument variable itself) passed to a parameter variable
Object is immutable, there is no possibility that value of the argument variable will be changed by a function call
www.cass.city.ac.uk
Passing a Value to a Function
Example: Program shows there is no change in the value of the argument
www.cass.city.ac.uk
Functions Having Several Parameters
Must be the same number of arguments as parameters in the function
Data types of arguments’ values must be compatible with data types expected by the parameters
Must also be in the same order
www.cass.city.ac.uk
Functions Having Several Parameters
Example: Program uses the user-defined function power with control from within a user defined function main
arguments
parameters
www.cass.city.ac.uk
Functions Having Several Parameters
Example: Program uses the user-defined function with control from within a user defined function main
Call defined function with function
Standard libraries
www.cass.city.ac.uk
The mainline Procedure
www.cass.city.ac.uk
Functions Having Several Parameters
Example: Function computes the balance in a saving account
www.cass.city.ac.uk
Boolean- and List-valued Functions
Example: Program uses Boolean-valued functions
www.cass.city.ac.uk
Boolean- and List-valued Functions
A possible mainline routine:
Call function
Call function
Control program execution through a user-defined function main
www.cass.city.ac.uk
Boolean- and List-valued Functions
Example: Program uses Boolean-valued functions
Execution control at the program level
www.cass.city.ac.uk
A Black-Scholes Option Pricing solution in python
.
www.cass.city.ac.uk
A Black-Scholes Option Pricing solution in python
www.cass.city.ac.uk
A Black-Scholes Option Pricing solution in python
www.cass.city.ac.uk
A Black-Scholes Option Pricing solution in python
www.cass.city.ac.uk
Scope of Variables
Variable created inside a function can only be accessed by statements inside that function
Ceases to exist when the function is exited
Variable is said to be local to function or to have local scope
If variables created in two different functions have the same name
They have no relationship to each other
www.cass.city.ac.uk
Scope of Variables
Scope of a variable is the portion of the program that can refer to it
To make a variable global, place assignment statement that creates it at top of program.
Any function can read the value of a global variable
Value cannot be altered inside a function unless
www.cass.city.ac.uk
Scope of Variables
Example: Program contains a global variable
Can update global variable
www.cass.city.ac.uk
Named Constants
Program sometimes employs a special constant used several times in program
Convention programmers use
Create a global variable
Name written in uppercase letters with words separated by underscore
In Python, programmer is responsible for not changing value of the variable
www.cass.city.ac.uk
USER-DEFINED FUNCTIONS
PART II
www.cass.city.ac.uk
Library Modules
A library module is a file with extension .py
Contains functions and variables
Can be used (imported) by any program
can be created in IDLE or any text editor
Looks like an ordinary Python program (save in the library directory)
To gain access to the functions and variables
place a statement of the form import moduleName
at the beginning of the program
www.cass.city.ac.uk
Library Modules
A very simple example of a module/library
File saved as simpleio.py in the lib (or any other) directory
Use the module
Assign to local variables
www.cass.city.ac.uk
58
Library Modules
File saved as fibo.py in the lib directory
A very simple example of a module/library
www.cass.city.ac.uk
THE NORMSIDIST
To compute the cumulative probabilities of a standard normal distribution, use the function n(..) in the file/module library normsdist i.e. included in the week 3 demos [.py]
You can insert the code as a function in the Black-Scholes example or import it as a library
i.e. run your program from the correct(same) directory
www.cass.city.ac.uk
THE NORMSIDIST
www.cass.city.ac.uk
Library Modules
Table Several modules from the standard library.
www.cass.city.ac.uk
USING THE os library & CLI COMMANDS
www.cass.city.ac.uk
63
Functions Calling Other Functions
Function can call another function
When the called function terminates
Control returns to the place in calling function just after where function call occurred (refer to example sin previous slides).
www.cass.city.ac.uk
Functions Returning Multiple Values
Functions can return any type of object
Function can return a tuple.
Example 2: balanceAndInterest function returns a tuple
Giving values associated with deposit into savings account.
www.cass.city.ac.uk
Functions Returning Multiple Values
Example
www.cass.city.ac.uk
Functions Returning Multiple Values
Example: Variation of previous slide solution; it has the input, processing, and output performed individually by three functions.
www.cass.city.ac.uk
List Comprehension
Simpler way to apply a certain function to each item of a list
Use list comprehension
The for clause in a list comprehension can optionally be followed by an if clause.
www.cass.city.ac.uk
List Comprehension
Table: Examples of list comprehension.
www.cass.city.ac.uk
Default Values
Parameters of a function can have default values
Assigned to them when no values are passed to them
Format for definition using default values
www.cass.city.ac.uk
Default Values
Table: Three function calls
www.cass.city.ac.uk
Passing by Parameter Name
Arguments can be passed to functions by using names of the corresponding parameters
Instead of relying on position
Given
Could use
www.cass.city.ac.uk
Passing by Parameter Name & function polymorphism
Example: Several ways to pass values
www.cass.city.ac.uk
READING THIS WEEK
Lecturer notes, which map to
EULER A. (assay): Module and Function Design
SCHNEIDER, I. D., (2015), An Introduction to Programming Using Python, Global Edition
Chapter 4
LAMBERT, A. K., (2012), Fundamentals of Python: First Programs, 1st Edition
Chapter 6
DEITEL M., H., DEITEL & ASSOCIATES, (2002), Python How to Program
Chapter 4
Optional
Ethics and professional standard considerations (reading)
Additional Resources
Python Tutorial:
http://docs.python.org/tut/
74
www.cass.city.ac.uk
HOMEWORK THIS WEEK and next week
See separate file on Moodle & MOCKS.
75
www.cass.city.ac.uk
Cass Business School
106 Bunhill Row
London EC1Y 8TZ
T: + 44 (0)20 7040 8600
www.cass.city.ac.uk
www.cass.city.ac.uk
(
)
(
)
(
)
)
d
(
N
Ke
d
N
e
S
c
2
r
1
q
0
t
–
t
–
–
=
(
)
(
)
(
)
)
d
(
N
Ke
d
N
e
S
p
2
r
1
q
0
–
+
–
–
=
t
–
t
–
(
)
(
)
[
]
t
s
t
s
+
–
+
=
2
1
5
.
0
q
r
K
/
S
ln
d
(
)
(
)
[
]
t
s
–
=
t
s
t
s
–
–
+
=
1
2
2
d
5
.
0
q
r
K
/
S
ln
d