0% found this document useful (0 votes)
27 views9 pages

Chap - 14

Uploaded by

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

Chap - 14

Uploaded by

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

Modular Design 14-1

Chapter
14

Modular Design
Key Topics
14.1. Introduction
14.1. Introduction
14.2. Software design Approaches
Modular design is a design approach that subdivides a system
14.2.1. Top Down Design into smaller parts called modules, which can be independently
14.3. Python Modules created and then used in different systems. This allows designs
14.4. Importing Modules In Python
14.4.1. Python Import Statement to be customized, upgraded, repaired and for parts to be reused.
14.4.2. Import with Renaming Modular design is a technique to divide a software system
14.4.3. Import Multiple Modules
14.4.4. Python from.... Import into multiple discrete and independent modules, which are
Statement expected to be capable of carrying out tasks independently. These
14.5. Python Built-in Modules
14.6. The Dir( ) Built-in Function modules may work as basic constructs for the entire software.
14.7. Python Packages Designers tend to design modules such that they can be executed
and/or compiled separately and independently.
Modular programming is the process of subdividing a
computer program into separate sub-programs. A module is a
software component or part of a program that contains one or
more routines. Similarly functions are grouped in the same unit
of programming code and separate functions are developed as
separate unit of code so that the code can be reused by other
applications. OOP is compatible with the modular programming
concept to a large extend. Here are some advantages of using
modular programming.
Advantage of Modular Programming.
1. Less code has to be written.
2. Faster development. Modular programming allows many
programmers to collaborate on the same application.
3. Easy debugging and maintenance as errors can easily be
identified, as they are localized to a subroutine or function.
14-2 Modular Design
4. Easy to understand as each module works independently to another module.
5. Several programmers can work on individual programs at the same time.
6. The scoping of variables can easily be controlled.
7. Modules can be re-used, eliminating the need to retype the code many times.
8. A single procedure can be developed for reuse, eliminating the need to retype the code many
times.

14.2. Software design Approaches


Here are two generic approaches for software designing:

14.2.1. Top Down Design


Top-down designing tends to generate modules that are based on functionality, usually in the
form of functions or procedures. Basically, it breaks programming into smaller subsections that are
further polished until they are readable. This approach was later replaced by C# and object oriented
programming, necessary for handling complex programs. Top-down design is more suitable when
the software solution needs to be designed from scratch and specific details are unknown. Some of
benefits of top-down designing approach are:
Easy to understand : Modularization is a common term in program design that means breaking
a program into smaller distinct pieces. Top down design are easy to understand, easy to update and
easy to debug. In any case, the computer only runs a set of instructions and doesn't care if the
software was written bottom-up, in OOP or top down.
Readable : The modules are easy to read since they are written using the tags of undefined
components. This process is done repetitively until every module is broken down to smaller piece.
An essential part of the strategy is to ensure that programmers can easily understand the block
code. Moreover, programmers can easily identify bugs that can make the program unreadable.
Code reuse : By using top down design in programming, software developers can reuse code
in various program fragments. That way, there is no need of writing new code every now and then.
Simply use the written functions in other program fragments.

14.3. Python Modules


Modules refer to a file containing Python statements functions, classes and definitions. All
these definitions and statements are contained in a single python file. The name of the module is the
name of file name with .py extension. We use modules to break down large programs into small
manageable and organized files. Furthermore, modules provide reusability of code. We can define
our most used functions in a module and import it, instead of copying their definitions into different
programs. To define a module, we use Python IDLE or any suitable text editor.
Type the following and save it as addmodule.py.

def add(a, b):


result = a + b
return(result)
Modular Design 14-3
So a file containing Python code i.e. addmodule.py is called a module. Here we have defined a
function add( ) inside a module name addmodule. This function takes two parameters a and b and
return their sum.

14.4. Importing Modules In Python


We can import the definitions inside a module to another module or the interactive interpreter in
Python. We use the import keyword to do this. To import our previously defined module example we
type the following in the Python prompt.

>>> import addmodule

This does not enter the names of the functions defined in addmodule directly in the current
symbol table. It only enters the module name addmodule there. Using the module name we can
access the function using dot (.) operation. For example:

>>> addmodule.add(4,5.5)
Output
9.5

Python has a ton of standard modules available. These files are in the Lib directory inside the
location where you installed Python. Standard modules can be imported the same way as we import
our user-defined modules. There are various ways to import modules. They are listed as follows.

14.4.1. Python Import Statement


We can import a module using import statement and access the definitions inside it using the
dot (.) operation as described in the example.
Syntax
import module1, module2, module3

The import statement should be at the starting of code. The import keyword is followed by one
or more python module specifiers separated by commas. When the interpreter encounters an import
statement, it imports the module present in the search path.

import math
print("The value of pi is", math.pi)
Output
The value of pi is 3.141592653589793

Python interpreter execute module body immediately. Python module is loaded only once. To
access attribute so module, we use object as prefix. In the above example math is standard module
name and function pi is standard defined in module.
14-4 Modular Design
14.4.2. Import with Renaming
We can import a module by renaming it as follows.

import math as ma
print("The value of pi is", ma.pi)
Output
The value of pi is 3.141592653589793

We have renamed the math module as ma. Note that the name math is not recognized in our
scope. Hence, math.pi is invalid, ma.pi is the correct implementation.
14.4.3. Import Multiple Modules
In order to use multiple modules, consider the following example.
circle.py
def circle(radius):
print(3.14*radius*radius)
return

rectangle.py
def rectangle(len,bre):
print(len*bre)
return

display.py
import circle, rectangle
circle.circle(4)
rectangle.rectangle(3,5)
Output
50.24
15

14.4.4. Python from.... Import Statement


In Python you can import specific names form a module without importing the module as a
whole. The syntax of which is as under:
Syntax: from <module_name> import <attribute1,attribute2,…..attributen>
from math import pi, sqrt, factorial
print("The value of pi is", pi)
n=int(input('Enter a Number'))
print("Square root of no: ",n , " = ", sqrt(n))
print("Factorial of no: ",n , " = ", factorial(n))
Modular Design 14-5

Output
The value of pi is 3.141592653589793
Enter a Number6
Square root of no: 6 = 2.449489742783178
Factorial of no: 6 = 720

Example 2: areas.py

def circle(r):
print(3.14*r*r)
return

def square(r):
print(r*r)
return

def rectangle(len,bre):
print(len*bre)
return

Then create another file named calculateara.py in which we import all the attributes from
areas.
calculatearea.py

from areas import circle,square,rectangle


radius_cir=int(input("To Calculate area of a Circle enter Radius :"))
circle(radius_cir)

len_rect=int(input("To Calculate area of a Square enter Length:"))


square(len_rect)

length=int(input("To Calculate area of a Rectangle enter Length :"))


bredth=int(input("To Calculate area of a Rectangle enter Bredth :"))
rectangle(length,bredth)
Output
To Calculate area of a Circle enter Radius :4

50.24

To Calculate area of a Square enter Length:3


14-6 Modular Design

To Calculate area of a Rectangle enter Length :4


To Calculate area of a Rectangle enter Bredth :3

12

#Program to Print Current Month Calendar


import calendar

year = int(input("Enter year: "))


month = int(input("Enter month: "))

# display the calendar


print(calendar.month(year, month))
Output
Enter year: 2017
Enter month: 5
May 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

14.5. Python Built-in Modules


There are many built-in modules in Python. Each module has a number of built-in functions
which can be used to perform various functions. Some of math built-in functions are:
Module.Function Description
math.ceil(x) Return the ceiling of x as a float, the smallest integer value greater
than or equal to x.
math.factorial(x) Return x factorial. Raises error if x is not integral or is negative.
math.floor(x) Return the floor of x as a float, the largest integer value less than
or equal to x.
math.pow(x, y) Return x raised to the power y
math.sqrt(x) Return the square root of x.
Modular Design 14-7

Module.Function Description
math.cos(x) Return the cosine of x radians.
math.sin(x) Return the sine of x radians.
Math.tan(x) Return the tangent of x radians.
math.pi The mathematical constant ? = 3.141592..., to available precision.
math.e The mathematical constant e = 2.718281..., to available precision.

14.6.The Dir( ) Built-in Function


The dir( ) function is to find out names that are defined inside a module.
The dir( ) function lists contains all the names of modules, variables and functions that are
defined in a module.

Example
import math
dir(math)
Output
['__doc__', '__loader__', '__name__', '__package__', 'acos', 'acosh', 'asin',
'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e',
'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
'gamma', 'hypot', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p',
'log2', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']

Here all names that begin with underscore are default Python attributes associated with the
module.
Example 2
As we have defined a function add( ) in the module addmodule that we had in the beginning.
and circle( ), rectangle( ), and square( ) in the module calculatearea in example 2.

import addmodule
dir(addmodule)
Output
['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__',
'__loader__', '__name__', '__package__', 'add']

Here, we can see a sorted list of names along with add. All other names that begin with an
underscore are default Python attributes associated with the module and we did not define them
ourself.
14-8 Modular Design

import calculatearea
dir(calculatearea)
Output
['__builtins__', '__cached__', '__doc__', '__file__', '__initializing__',
'__loader__', '__name__', '__package__', 'bredth', 'circle', 'len_rect',
'length', 'radius_cir', 'rectangle', 'square']

Here, we can see a sorted list of names along with circle, rectangle and square which are
imported from areas.py.

14.7. Python Packages


In Python packages we divide our code base into clean, efficient modules using Python packages.
Also, you'll learn to import and use your own or third party packages in your Python program.
We don't usually store all of our files in our computer in the same location. We use a well-
organized hierarchy of directories for easier access. Similar files are kept in the same directory, for
example, we may keep all the C Language Programs in the "CLanguage" directory.
Similarly Python has packages for directories and modules for files.
As our application program grows larger in size with a lot of modules, we place similar modules
in one package and different modules in different packages. This makes a project (program) easy to
manage and conceptually clear. Similar, as a directory can contain sub-directories and files, a Python
package can have sub-packages and modules.
A directory must contain a file named __init__.py in order for Python to consider it as a
package. This file can be left empty but we generally place the initialization code for that package in
this file.

Frequently Asked Questions


Q.1. What is module? Why it is needed? What do you mean by Python modules?
Q.2. What is top-down approach? List benefits of top-down approach.
Q.3. How modules are accessed in Python?
Q.4. How we can import in-build modules? Explain with the help of example.
Q.5. What is the purpose of dir( ) function in modules. Explain with the help of example.
Q.6. What are packages in Python?

You might also like