Modular Programming, Types of Modules & User-Defined Modules
Overview: Put a grading function in grades.py and import it from the marks-entry script.
What is Modular Programming & Why is it Important?
- Modular Programming is a software design technique that divides a large, complex program into smaller, independent, and reusable files…
- Importance / Advantages of Modular Programming: Code Reusability: Write a module once and import it into multiple projects without rewriting code.
- Simplicity & Readability: Smaller files (100–200 lines) are much easier to understand than one giant 5,000-line file.
- Easy Debugging & Maintenance: If an error occurs in billing, you only need to check
billing.py. - Team Collaboration: Different developers can work on different modules simultaneously without conflict.
- Avoids Naming Collisions (Separate Namespaces): Two modules (
module1.pyandmodule2.py) can both have a function namedcalculate()without clashing.
View diagram · Modular Programming Architecture in Python
What is a Module in Python?
- A Module in Python is simply any file with a
.pyextension that contains executable Python code — such as **functions, classes, and…
Types of Modules in Python
- Python modules are divided into two main categories:
- Definition: Modules that come pre-installed with Python’s Standard Library
- Creation: Written by Python core developers (in C or Python)
- Installation: Ready to use immediately with
import - Examples:
math,os,sys,datetime,random,re,json
Creating and Importing a User-Defined Module
- Let’s create our own module and use it inside another Python program!
- Step 1: Create the Module File (
mycalc.py): Save the following code in a file namedmycalc.py: - Step 2: Import and Use
mycalcinmain.py: In the same folder, createmain.py. - Way 1: Standard
import module_name: Imports the whole module. - Way 2: Importing with an Alias (
import module as alias): Gives a short nickname to the module name: - Way 3: Importing Specific Items (
from module import item1, item2): Imports only selected functions/variables directly, so you don’t need the module prefix: - Way 4: Importing Everything (
from module import *): Imports all functions and variables from the module (generally not recommended for large programs as it can cause name clashes):
Useful Built-in Module Inspection Tools
- The
dir()Function: Lists all functions, classes, and variables defined inside a module. - The
__name__ == "__main__"Idiom: - When a Python file is run directly, its built-in
__name__variable is set to"__main__". - When the file is imported as a module into another file,
__name__is set to the module’s filename ("mycalc"). - Putting test code inside
if __name__ == "__main__":ensures the test code runs only when the file is executed directly, and not when…
Standard Modules in Python: math, datetime, and os
Overview: Use datetime to work out how many days remain until an exam, math for a square root, and os for operating-system services.
The math Module
- The
mathmodule provides fast mathematical functions and constants. - Important Constants in
math:math.pi→ Value of Pi (3.141592653589793) math.e→ Euler’s number (2.718281828459045)math.sqrt(x): Returns the square root ofxas afloatmath.pow(x, y): Returnsxraised to poweryas afloatmath.ceil(x): Rounds a float UP to the nearest integermath.floor(x): Rounds a float DOWN to the nearest integermath.factorial(x): Returns the factorial ofx(x!)
The datetime Module
- The
datetimemodule provides classes for manipulating dates and times in both simple and complex ways. - Main Classes Inside
datetimeModule:datetime.dateRepresents a calendar date (year,month,day). datetime.timeRepresents time of day (hour,minute,second,microsecond).datetime.datetimeCombines bothdateandtimeinto a single object.datetime.timedeltaRepresents the difference (duration) between two dates or times (used for adding/subtracting days).- Formatting Dates with
strftime()(String Format Time): Thestrftime()method converts adatetimeobject into a readable formatted string: %d→ Day of month (01to31)%m→ Month number (01to12)
The os Module (Operating System Interface)
- The
osmodule allows your Python program to interact directly with the underlying Operating System (Windows, Linux, macOS) to manage… os.name: Returns the OS kernel name ('nt'for Windows,'posix'for Linux/Mac)os.getcwd(): Returns the Current Working Directory (folder path)os.chdir(path): Changes the current working directory topathos.listdir(path): Returns a list of all files and folders insidepathos.mkdir("folder"): Creates a single new folder (directory)os.makedirs("a/b/c"): Creates nested folders recursively
Python Packages: Pre-defined, User-defined & Package vs Folder
Overview: A package groups related modules under a shared import name, such as college.results.
What is a Package in Python?
- A Package is a directory (folder) that contains multiple related Python modules (
.pyfiles) along with a special initialization file… -
- Function: A single chapter or recipe.
-
- Module (
.pyfile): A book containing related chapters (functions & classes).
- Module (
-
- Package (Directory with
__init__.py): A bookshelf/library section that organizes multiple related books (modules).
- Package (Directory with
- Role of
__init__.py: The__init__.pyfile tells Python that the directory should be treated as an importable Package. - It can be completely empty, or it can contain package initialization code and specify which modules to expose when someone imports the…
View diagram · Organizing a Python Project into a Package (college_pkg)
Types of Packages in Python
- Just like modules, Python packages are classified into two types:
- A. Pre-Defined (Built-in & Third-Party) Packages: Packages created by the Python community or core developers that provide ready-made functionality:
- Standard Library Packages (Pre-installed with Python):
tkinter(GUI development)urllib(Working with URLs and HTTP requests)xmlandjson(Data parsing)unittest(Automated software testing)- Third-Party Packages (Installed via
pip install <package>from PyPI):
Step-by-Step: Creating and Using a User-Defined Package
- Let’s create the
college_pkgpackage shown above and use it insidemain.py. - Step 1: Create folder
college_pkgand add__init__.py: Insidecollege_pkg/__init__.py: - Step 2: Create modules inside
college_pkg/: Insidecollege_pkg/students.py:
Package vs Folder (Directory)
- Students often ask: “Is every folder on my computer a Python package?” No! Here is the exact difference:
- Definition: A namespace directory containing Python
.pymodules and an__init__.pyfile - Role of
__init__.py: Contains__init__.pyto initialize package-level state - Purpose: Organizes Python modules so they can be imported using dot notation (
import pkg.mod) - Importability: Can be imported in Python scripts using
import
Quick Comparison: Module vs Package
- What is it?: A single Python file with a
.pyextension - Scope: Groups related functions, classes, and variables
- Example:
math.py,random.py,students.py
File and Directory Handling in Python
Overview: Opening a file with mode w truncates an existing file.
Opening a File & File Access Modes
- In Python, we use the built-in
open(filename, mode)function to open a file. 'r': Read (Default)'w': Write'a': Append'x': Exclusive Create'r+': Read + Write'w+': Write + Read
Writing Data to a File (write() and writelines())
f.write(string): Writes a single string to the file.f.writelines(list_of_strings): Writes multiple strings from a list to the file.
Reading Data from a File (read(), readline(), readlines())
f.read(): Reads the entire file and returns it as a single string (f.read(n)readsncharacters)f.readline(): Reads only one single line from the file at a timef.readlines(): Reads all lines and returns them as a List of strings- Best Practice: The
with open(...)Statement (Context Manager): When you open a file using thewithkeyword, Python automatically closes the file as soon as the block finishes (even…
Moving the File Cursor: tell() and seek()
- When reading or writing a file, Python maintains an internal File Pointer (Cursor) that tracks your current byte position.
f.tell(): Returns the current position (in bytes) of the file pointer from the beginning of the file.f.seek(offset): Moves the file pointer to a specific byte position (f.seek(0)resets the cursor back to the very beginning of the…
Directory (Folder) Handling in Python
- Python uses the
osandshutilmodules to create, inspect, rename, and delete directories (folders):