0% found this document useful (0 votes)
24 views28 pages

Modular Design

Uploaded by

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

Modular Design

Uploaded by

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

Modular Design: Modules

Modular Programming
Modular programming is a technique that simplifies complex software
development by breaking it down into smaller, manageable pieces called
modules. Each module performs a specific task and can be used independently
or combined with other modules to build larger systems. This approach offers
several benefits such as easier code maintenance, update simplicity, and the
reusability of code across projects.
 Modular programming organizes code into distinct sections with specific
functions.
 Key principles include high cohesion within modules and loose coupling
between them.
 Advantages include easier updates, reusability of code, and efficient
teamwork.
 Challenges might involve increased code volume and complexity for
smaller projects.

Here are some key points about modular programming:


 Abstraction - Modules focus on doing a specific job and hide how they do
it from the rest of the program. This means you can use a module without
knowing the details of how it works.
 Encapsulation - Modules bundle together everything they need to do their
job, like data and procedures. This keeps things tidy and under control.
 Information hiding - Modules only show the necessary parts to the
outside world, keeping their inner workings private. This helps prevent
other parts of the program from relying too much on how a module does
its job, which can change.
Modular programming started in the late 1960s to help manage growing and
more complex software systems. It's a smart way to organize programs, making
them easier to build, test, fix, and reuse. Nowadays, it's a fundamental part of
designing and building software.
[One of the first languages designed from the start for modular programming
was the short-lived Modula (1975), by Niklaus Wirth.]
Core Principles of Modular Programming
The main ideas behind modular programming include:
 High cohesion - Everything inside a module is closely related and works
towards the same goal.
 Loose coupling - Modules connect with each other only through their
outer layers, so they don't need to know much about each other to work
together.
 Abstraction - Modules hide their inner workings, showing only what's
needed for them to be used.
 Self-containment - Modules have all they need to function on their own,
reducing dependence on outside parts.
Following these principles makes modules easier to handle, test, fix, add to, and
reuse. Changes in one module won't mess up others, and it's easier to keep track
of where problems might be.
Modular Programming vs Traditional Programming

Modular Programming Traditional Programming

Focus on keeping things related


and wrapped up nicely Often mixes different things together
Keeps details hidden and shows
only what's needed Less careful about hiding details
Modules are loosely connected Parts are tightly intertwined
Easier to manage dependencies Dependencies can be a mess
Allows for working on different Usually, you work on one thing after
parts at the same time another
Makes it easier to use parts again Reusing parts can be tricky

Definition of Module
A module in Python is a file that contains Python code, such as functions,
variables, classes, or methods, that can be imported into another Python
program:
Modules are similar to code libraries and help to organize Python code
logically. They can be used to group related code into a single file, making it
easier to understand and use.

Components of a Module
A module is like a little box that contains three main things:
 Interface - This is the part of the module that talks to the outside world.
It's like a list of commands that other parts of the program can use.
 Implementation - This is the secret sauce inside the module. It's all the
code and steps that make the module work but aren't shown to everyone.
 Data structures - These are like the module's personal notebooks. They
hold all the information the module needs to do its tasks. Keeping this
info inside the module helps keep things neat and tidy.
Types of Modules
Modules can be different kinds:
 Program control modules - These are the bosses. They manage how the
program starts, ends, deals with mistakes, interacts with users, and makes
sure other modules are working together nicely.
 Specific task modules - These are the specialists. They focus on doing
one thing really well, like working with numbers, managing text, or
talking to devices.
For example, in Python programming:
 import platform - that provides system information.
 import math - Deals with mathematical functions.
 import datetime - display the current date
Modular Design Patterns
Here are some design patterns that help with modular programming:
 Facade - Makes a simple front for more complex interactions between
modules.
 Adapter - Lets modules that normally wouldn't work together connect
through a middleman.
 Bridge - Keeps the big ideas separate from the nitty-gritty details, so you
can change them independently.
Using these patterns can help keep the connections between modules clean and
easy to manage.
Advantages of Modular Programming
 Easier to keep up - Since each part does its own thing, updating, fixing, or
adding new stuff doesn't mess with the rest. Different developers can
work on their own parts at the same time.
 Use parts again - You can take a module you've made and use it in
another project. This saves time because you don't have to start from
scratch every time.
 Simpler to handle - Splitting a big program into smaller parts makes it
less overwhelming. It's easier to figure out what's going on, which helps
when you're building or fixing things.
 Work together better - Teams can work on different parts at the same
time. This means you can finish big projects faster.
 Neater projects - Putting related stuff together in modules makes your
project more organized. This helps when you're dealing with a lot of
code.
Modular Programming in Industry
 TinyMCE breaks down the editing process into over 30 specific modules
for different tasks. This makes it quick to set up different versions of their
editor.
 Amazon designed Polly, their talking text service, with modules so you
can change how it speaks easily.
 Spotify uses a similar idea but for their teams, allowing them to work on
small parts of the app independently. This helps them make changes
faster.
Top-Down Design
Top-Down Design is a problem-solving approach that starts with the highest-
level overview of a system and progressively breaks it down into smaller, more
manageable components. In Python, this method can be particularly effective
for structuring your code in a clear and organized manner.

Steps for Top-Down Design


1. Define the overall system requirements:
The first step is to define the overall goals and objectives of the system,
as well as any specific requirements or constraints.
2. Break down the system into smaller components:
Next, the system is broken down into smaller, more manageable
components or modules.
3. Develop each component individually:
Once the system has been divided into smaller components, each
component can be developed individually.
4. Test and debug each component:
As each component is developed, it is important to test and debug it to
ensure that it is working properly.
5. Integrate the components:
After each component has been developed and tested individually, they
can be integrated into the larger system.
6. Test the entire system:
Once all of the components have been integrated, the entire system can be
tested to ensure that it is functioning as intended.
7. Maintain and update the system:
After the system has been implemented, it will need to be maintained and
updated on an ongoing basis to fix any bugs or to add new features.
Example:

PYTHON Modules

 File extension: Python modules have a file extension of .py.


 Creating modules: To create a module, save the code you want in a file
with the .py extension.
 Importing modules: To import a module, use the import statement.
 Built-in modules: Some modules are available through the Python
Standard Library and are installed with Python.
 Installing modules: Other modules can be installed with Python's
package manager pip.
 Best practices: When writing large Python code blocks for production-
level projects, it's recommended to split the code into modules that
contain up to 300–400 lines of code.
Creating a Module
1. Create a New Python File: Let's create a module called
math_operations.py. This file will contain some basic mathematical
functions.
# math_operations.py

def add(x, y):


"""Return the sum of x and y."""
return x + y

def subtract(x, y):


"""Return the difference of x and y."""
return x - y

def multiply(x, y):


"""Return the product of x and y."""
return x * y

def divide(x, y):


"""Return the quotient of x and y, handling division by zero."""
if y == 0:
return "Error! Division by zero."
return x / y
Using a Module
2. Import the Module in Another File: Now, create another Python file, for
example, calculator.py, where we will use the math_operations module.

# calculator.py
import math_operations
def main():
print("Simple Calculator")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")

if operation == '+':
result = math_operations.add(num1, num2)
elif operation == '-':
result = math_operations.subtract(num1, num2)
elif operation == '*':
result = math_operations.multiply(num1, num2)
elif operation == '/':
result = math_operations.divide(num1, num2)
else:
result = "Invalid operation!"

print("Result:", result)

main()
Benefits of Using Modules
 Code Reusability: Functions can be reused across different programs
without rewriting code.
 Organization: Code is organized into separate files, making it easier to
manage and maintain.
 Collaboration: Different team members can work on different modules
without conflicts.

Python Built in Modules


Few Examples
1. math
The math module provides mathematical functions, including trigonometric and
logarithmic functions.
Example:
import math

# Calculate the square root of a number


number = 16
sqrt_value = math.sqrt(number)
print("Square root of", number, "is", sqrt_value)

# Calculate the sine of an angle (in radians)


angle = math.pi / 2 # 90 degrees
sine_value = math.sin(angle)
print("Sine of 90 degrees is", sine_value)
2. random
The random module is used for generating random numbers and making
random selections.
Example:
import random

# Generate a random integer between 1 and 10


random_integer = random.randint(1, 10)
print("Random integer:", random_integer)

# Select a random element from a list


colors = ['red', 'green', 'blue']
random_color = random.choice(colors)
print("Random color:", random_color)
3. datetime
The datetime module provides classes for manipulating dates and times.
Example:
from datetime import datetime

# Get the current date and time


now = datetime.now()
print("Current date and time:", now)

# Format the date


formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date:", formatted_date)
4. os
The os module provides a way to interact with the operating system, allowing
you to work with files and directories.
Example:
import os

# Get the current working directory


current_directory = os.getcwd()
print("Current directory:", current_directory)
# List files in the current directory
files = os.listdir(current_directory)
print("Files in directory:", files)
5. sys
The sys module provides access to some variables used or maintained by the
interpreter and allows interaction with the Python runtime environment.
Example:
import sys

# Print the Python version


print("Python version:", sys.version)

# Print command-line arguments


print("Command-line arguments:", sys.argv)
6. json
JSON is a syntax for storing and exchanging data.
JSON is text, written with JavaScript object notation.

The json module is used to work with JSON data, allowing you to encode and
decode JSON.
Example:
import json

# Create a Python dictionary


data = {'name': 'Arun', 'age': 30}

# Convert the dictionary to a JSON string


json_data = json.dumps(data)
print("JSON data:", json_data)

# Convert JSON back to a Python dictionary


parsed_data = json.loads(json_data)
print("Parsed data:", parsed_data)
7. time
The time module provides various time-related functions, including time
manipulation and formatting.
Example:
import time

# Pause the program for 2 seconds


print("Waiting for 2 seconds...")
time.sleep(2)
print("Done waiting!")
8. re
The re module provides support for regular expressions, allowing you to search,
match, and manipulate strings.
Example:
import re

# Search for a pattern in a string


pattern = r'\d+' # Matches one or more digits
text = "There are 123 apples"

match = re.search(pattern, text)


if match:
print("Found digits:", match.group())
Text Files
Python provides built-in functions for creating, writing, and reading files. Two
types of files can be handled in Python, normal text files and binary files
(written in binary language, 0s, and 1s).
 Text files: In this type of file, Each line of text is terminated with a
special character called EOL (End of Line), which is the new line
character (‘\n’) in Python by default.
 Binary files: In this type of file, there is no terminator for a line, and the
data is stored after converting it into machine-understandable binary
language.

File Operations:
 Opening a Text File
 Read Text File
 Write to Text File
 Appending to a File
 Closing a Text File
File Access Mode
The access mode parameter serves as the determinant of the specific
mode in which the file is to be opened, thereby dictating whether
operations such as reading, writing, appending, etc., are permissible. Here
is a list of the different modes of opening a file:
The functions in Python that allow to read and write to files:
 read() : This function reads the entire file and returns a string
 readline() : This function reads lines from that file and returns as a string.
It fetch the line n, if it is been called nth time.
 readlines() : This function returns a list where each element is single line
of that file.
 readlines() : This function returns a list where each element is single line
of that file.
 write() : This function writes a fixed sequence of characters to a file.
 writelines() : This function writes a list of string.
 append() : This function append string to the file instead of overwriting
the file.
 close(): This function closes the file and frees the memory space acquired
by that file.

How to open a file in Python

Python has a built-in function open() to open the file.

 open () returns a file object that is called a handle.

 It is used to read or modify the file.

Syntax

x = open (file_name, access_mode)

file_name: The name of the file that you want to open

Example:

#open a file
o = open ('nl.txt') #it is a default mode, i.e. read only mode

o = open ('nl_txt', w) #it will open the file for writing

How to read a file in Python

To read a file in Python, the file must first be opened in the read mode.

 Python offers several methods of reading.

 If you want a read-only first line only, use readline (), and if you
want to read all the lines in the form of lines, use readlines ()

 If you want to read a few characters of the file, use read (size)

 read () used to read all the content at a time.

Example:

#read a file

nl = open('nl.txt','r') # it will open the file in read mode

nl.readline() # it will read the first line of the file

nl.read(10) # it will read the first 10 charcter of the file

nl.read() # it will return the whole text

How to Create a new file in Python

To create a new file, we have to open a file using one of the two parameters:

x: it will create a new empty text file iff there does not exist any file with the
same name; otherwise, it will throw an error
w: it will create a file, whether any file exists with the same or not, i.e., it will
not return an error if the same file name exists.

Example:

#create a file

nl = open ('nl.txt', 'x') # it will create a new empty file but will throw an error if
the same file name exists

nl = open ('nl.txt', 'w') # it will create a file but if the same file name exist it will
overwrite

How to Write in an existing file in Python

Python offers two methods to write in an existing file:

 write () method

 It will add a single line at a time

Example:

# write into an existing file

with open('nl.txt','w') as nl:

nl.write('This is the first line\n')

nl.write('This is the second line\n')

nl.write('this is the third line')


writelines () method

 It allows to insert multiple string at a time

Example:

nl = open('nl.txt', w)

#it allows to write all the line in one go

nl.writelines('This is the first line\n', 'This is the second line\n', 'This is the third
line')

nl.close()

How to close a file in Python

Once you are done with all the operations, you need to close the file correctly.

 The close () commands will terminate all the resources and will free the
system

 It is a good practice to close the file.

Example

#close a file

nl = open('nl.txt', 'r')

print(nl.read())

nl.close()
Exception Handling
Exception handling in Python is the process of responding to unexpected
errors that occur while a program is running.
The goal of exception handling is to prevent the program from crashing and to
allow the interpreter to execute the rest of the code.
three types of errors in Python:
1. Syntax or parsing errors
2. Runtime Errors [Your code may be syntactically correct, but if Python
encounters something it cannot handle during runtime, it will throw an
exception.]
3. Logical Errors [
Python Exceptions:
Exceptions are abnormal conditions that occur during program execution, such
as dividing by zero, adding incompatible types, or accessing a non-existent file.
Handling exceptions
Exceptions are handled using the try and except block. You can use multiple
except blocks to handle different types of exceptions.
Built-in exceptions
Python has many built-in exceptions, including ZeroDivisionError, TypeError,
FileNotFoundError, and ImportError.
Raising exceptions
You can also explicitly raise an exception if a certain condition occurs. To do
this, use the raise keyword.
The finally clause
The finally clause is an optional clause that executes regardless of whether an
exception occurs. It can be used to define clean-up actions.

Advantages of Exception Handling:


 Improved program reliability
 Simplified error handling
 Cleaner code
 Easier debugging
Disadvantages of Exception Handling:
 Performance overhead.
 Increased code complexity
 Possible security risks
Features Errors Exceptions
Issues that occur during the Events that occur during program
Definition execution of the program that execution that disrupt the normal
are usually fatal. flow of instructions.
SyntaxError, IndentationError, ValueError, IndexError, KeyError,
Types
TypeError, etc. etc.
Cannot be handled; program Can be handled using try-except
Handling
usually terminates. blocks.
Cause Often due to incorrect code or Often due to logical errors or
environment issues. unexpected input.
Usually severe and may stop Can be caught and handled,
Severity
program execution. allowing the program to continue.
ZeroDivisionError (division by
SyntaxError (invalid syntax),
Examples zero), FileNotFoundError (file not
MemoryError (out of memory).
found).

Built-in Python Exceptions


Here is the list of default Python exceptions with descriptions:
1. AssertionError: raised when the assert statement fails.
2. EOFError: raised when the input() function meets the end-of-file
condition.
3. AttributeError: raised when the attribute assignment or reference fails.
4. TabError: raised when the indentations consist of inconsistent tabs or
spaces.
5. ImportError: raised when importing the module fails.
6. IndexError: occurs when the index of a sequence is out of range
7. KeyboardInterrupt: raised when the user inputs interrupt keys (Ctrl + C
or Delete).
8. RuntimeError: occurs when an error does not fall into any category.
9. NameError: raised when a variable is not found in the local or global
scope.
10.MemoryError: raised when programs run out of memory.
11.ValueError: occurs when the operation or function receives an argument
with the right type but the wrong value.
12.ZeroDivisionError: raised when you divide a value or variable with
zero.
13.SyntaxError: raised by the parser when the Python syntax is wrong.
14.IndentationError: occurs when there is a wrong indentation.
15.SystemError: raised when the interpreter detects an internal error.

Detailed View :

Syntax :
try:
# Some Code....
except:
# optional block
# Handling of exception (if required)
else:
# Execute if no exception
finally:
# Some code ....(always executed)

Working of ‘try’ and ‘except’


 First try clause is executed i.e. the code between try and except clause.
 If there is no exception, then only try clause will run, except clause will
not get executed.
 If any exception occurs, the try clause will be skipped and except clause
will run.
 If any exception occurs, but the except clause within the code doesn’t
handle it, it is passed on to the outer try statements. If the exception is left
unhandled, then the execution stops.
 A try statement can have more than one except clause.

Simple example
# put unsafe operation in try block
try:
print("code start")

# unsafe operation perform


print(1 / 0)

# if error occur the it goes in except block


except:
print("an error occurs")

Multiple except statement example


try:
x = int(input("Enter a number: "))
result = 10 / x
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Invalid input. Please enter a valid number.")
except Exception as e:
print(f"An error occurred: {e}")

Output:
Enter a number: An error occurred: EOF when reading a line

try with else Clause


When the `try` statement does not raise an exception, code enters into the `else`
block. It is the remedy or a fallback option when you expect a part of your script
will produce an exception. It is generally used in a brief setup or verification
section where you don't want certain errors to hide.
Note: In the try-except block, you can use the `else` after all the `except`
statements.
Simple example
# Python code to illustrate working of try()
def divide(x, y):
try:
# Floor Division : Gives only Fractional
# Part as Answer
result = x // y
except ZeroDivisionError:
print("Sorry ! You are dividing by zero ")
else:
print("Yeah ! Your answer is :", result)

# Look at parameters and note the working of Program


divide(3, 2)
divide(3, 0)
Output:
Yeah ! Your answer is : 1
Sorry ! You are dividing by zero

finally Keyword in Python


The `finally` keyword in the try-except block is always executed, irrespective of
whether there is an exception or not. In simple words, the `finally` block of code
is run after the try, except, the else block is final. It is quite useful in cleaning up
resources and closing the object, especially closing the files.

Example:
try:
numerator = 10
denominator = 0

result = numerator/denominator

print(result)
except:
print("Error: Denominator cannot be 0.")

finally:
print("This is finally block.")

Nested Exception Handling in Python


We need nested exception handling when we are preparing the program to
handle multiple exceptions in a sequence.
Example :
a=10
b=0
try:
print (a/b)
try:
print ("This is inner try block")
except Exception:
print ("General exception")
finally:
print ("inside inner finally block")

except ZeroDivisionError:
print ("Division by 0")
finally:
print ("inside outer finally block")

Raising Exceptions in Python


To throw an exception, we have to use the `raise` keyword followed by an
exception name.
Example 1:
# Python program to raise an exception
# divide function
def divide(a, b):
if b == 0:
raise Exception(" Cannot divide by zero. ")
return a / b
try:
result = divide(10, 0)
except Exception as e:
print(" An error occurred: ", e)
Output:
An error occurred: Cannot divide by zero.
Example 2:
# Python program to raise an exception
# check_age function checks the age
def check_age(age):
if age < 18:
raise Exception(" Age must be 18 or above. ")
else:
print(" You are eligible for voting. ")
try:
check_age(17)
except Exception as e:
print(" An error occurred: ", e)

Output:
An error occurred: Age must be 18 or above.

Interview purpose:
Both unit testing and exception handling are the core part of Python
programming that makes your code production-ready and error-proof. In this
topic, we have learned about exceptions and errors in Python and how to handle
them. Furthermore, we have learned about complex nested try-except blocks
and created custom exception blocks based on requirements.
These tools and mechanisms are essential, but most of the work is done through
simple `try` and `except` blocks. Where `try` looks for exceptions raised by the
code and `except` handles those exceptions.

You might also like