In Python, a module is a single file containing Python definitions and executable statements with a .py extension. The file name is the module name with the suffix .py appended (for example, a file named geometry.py is a module named geometry). A module can define functions, classes, and variables, and can also include runnable initialization code.
main.py file containing UI, math formulas, database queries, and email logic. Impossible to debug, test, or share across team members.calculator.py (Math), auth.py (Security), db.py (Storage). Main file simply imports what it needs!tax_engine.py, you can import and use it in 50 different projects without ever copying and pasting code.login(). If everything was in one file, the names would clash. Modules create separate namespaces: customer.login() and admin.login() coexist without conflicts!banking.py. The other 99 files in the software continue working untouched.| Concept | What It Represents | File System Form | Example |
|---|---|---|---|
| Script | A Python file designed to be executed directly from top to bottom by a user. | Single .py file |
python run_backup.py |
| Module | A Python file intended to be imported into other files for reuse. | Single .py file |
import math |
| Package | A directory collection of multiple modules with an __init__.py file. |
Folder containing .py files |
import urllib.request |
| Library | A large collection of related packages solving an entire domain problem. | Bundle of packages | numpy, pandas, django |
When Python encounters an import my_module statement, CPython performs three sequential actions:
my_module.py in the folders listed in sys.path.__pycache__/ directory as a .pyc file for high-speed subsequent imports.sys, time).pip.| Syntax Form | How to Access Contents | Advantages / Warnings |
|---|---|---|
import math |
math.sqrt(25) |
Clean & Safe: Prevents any naming clashes; keeps module origin crystal clear. |
import math as m |
m.sqrt(25) |
Aliasing: Shortens long module names (e.g. import numpy as np). |
from math import sqrt, pi |
sqrt(25), pi |
Direct Import: No need to type module prefix. Imports only required functions. |
from math import * |
sqrt(25), sin(0) |
⚠️ Anti-Pattern (Wildcard): Pollutes current namespace; can silently overwrite your own variables. Avoid! |
# Form 1: Standard import
import math
print("Standard import:", math.factorial(5))
# Form 2: Aliased import
import math as m
print("Aliased import :", m.sqrt(64))
# Form 3: Direct selective import
from math import pi, ceil, floor
print(f"Direct import : PI={pi:.4f}, Ceil={ceil(4.2)}, Floor={floor(4.8)}")
if __name__ == '__main__': Construct (A Universal Exam Question!)Every Python module has a built-in string attribute called __name__:
python my_script.py), Python sets __name__ = "__main__".import my_script), Python sets __name__ = "my_script".By placing code inside if __name__ == '__main__':, you ensure that test runs or demo statements only execute when the file is run directly, and are silently ignored when the file is imported elsewhere!
Python is celebrated for its "Batteries Included" philosophy: when you install Python, you automatically receive a vast library of thoroughly tested, optimized built-in modules.
math Module: Precision Mathematical FunctionsThe math module provides access to underlying C-library mathematical functions. Note that all math functions operate on floating-point numbers (for complex numbers, Python provides the separate cmath module).
import math
# Constants
print("--- Constants ---")
print("Value of Pi (π):", math.pi)
print("Value of Euler's (e):", math.e)
# Rounding & Arithmetic
print("\n--- Arithmetic Functions ---")
print("Square Root of 144 :", math.sqrt(144))
print("Ceiling of 7.15 :", math.ceil(7.15)) # Rounds UP -> 8
print("Floor of 7.85 :", math.floor(7.85)) # Rounds DOWN -> 7
print("Power 2^5 :", math.pow(2, 5))
print("GCD of (48, 64) :", math.gcd(48, 64))
random Module: Pseudo-Random Number GenerationThe random module implements pseudo-random number generators (PRNG) using the proven Mersenne Twister algorithm. It is ideal for simulations, dice rolling, games, and statistical sampling.
import random
# 1. Random float between 0.0 and 1.0
print("random.random() :", round(random.random(), 4))
# 2. Random integer between [min, max] INCLUSIVE
dice_roll = random.randint(1, 6)
print("Rolling 6-sided dice:", dice_roll)
# 3. Random choice from a collection
fruits = ["Apple", "Banana", "Cherry", "Mango", "Orange"]
chosen_fruit = random.choice(fruits)
print("Randomly selected fruit:", chosen_fruit)
# 4. In-place shuffling of a list
cards = ["Ace", "King", "Queen", "Jack", "10"]
random.shuffle(cards)
print("Shuffled deck cards :", cards)
# 5. Non-repeating sample (lottery selection)
lucky_draw = random.sample(range(1001, 1050), 3)
print("3 Lottery Winners :", lucky_draw)
datetime Module: Dates, Clocks, and Date ArithmeticThe datetime module supplies classes for manipulating dates and times in both simple and complex ways. The two most common operations are date arithmetic using timedelta and formatting dates with strftime().
import datetime
# Current exact date and time
now = datetime.datetime.now()
print("Current Timestamp:", now)
# Formatting with strftime (String Format Time)
formatted_date = now.strftime("%A, %d %B %Y | %I:%M %p")
print("Formatted Banner :", formatted_date)
# Date Arithmetic using timedelta
today = datetime.date.today()
exam_date = today + datetime.timedelta(days=45)
print(f"Today: {today} | University Exams in 45 days: {exam_date}")
os Module: Operating System & File System InteractionsThe os module provides a portable way of using operating system dependent functionality. It allows Python programs to create directories, read file paths, inspect directory contents, and check file existence across Windows, Linux, and macOS without modifying code.
import os
# 1. Current Working Directory
current_dir = os.getcwd()
print("Current Directory:", current_dir)
# 2. Constructing cross-platform file paths (uses \ on Windows, / on Linux)
file_path = os.path.join(current_dir, "student_database.csv")
print("Constructed Path :", file_path)
# 3. Checking if file exists
exists = os.path.exists(file_path)
print(f"Does file exist? : {exists}")
# 4. Listing directory contents (first 3 items)
dir_items = os.listdir(current_dir)
print(f"Folder contains {len(dir_items)} items. First 3: {dir_items[:3]}")
sys Module: Python Interpreter System ParametersThe sys module provides access to variables and functions maintained directly by the Python interpreter. It is essential for command-line arguments (sys.argv), inspecting search paths (sys.path), and halting program execution (sys.exit()).
import sys
# 1. Python Interpreter Version
print("Python Version:", sys.version.split()[0])
print("Running on OS :", sys.platform)
# 2. Command-Line Arguments passed to script
print("\nCommand-line arguments (sys.argv):", sys.argv)
# 3. Module Search Paths (sys.path)
print(f"\nsys.path contains {len(sys.path)} search directories.")
print("Primary search folder (CWD):", sys.path[0])
Creating your own module in Python does not require special commands or compilers. Any Python file you create is automatically a module! To use it, simply save functions and constants in a .py file and import it into another script within the same directory.
"""
Module Name: grade_calculator.py
Description: User-defined module providing grading utilities.
"""
PASSING_PERCENTAGE = 40.0 # Module Constant
def calculate_percentage(obtained, total):
"""Computes percentage rounded to 2 decimal places."""
if total <= 0:
return 0.0
return round((obtained / total) * 100, 2)
def assign_letter_grade(percentage):
"""Assigns university letter grade based on percentage."""
if percentage >= 85: return "A+"
elif percentage >= 70: return "A"
elif percentage >= 50: return "B"
elif percentage >= PASSING_PERCENTAGE: return "C"
else: return "F (Fail)"
# Self-test block: Only runs when executing this file directly!
if __name__ == "__main__":
print("[SELF-TEST] Testing module logic...")
test_pct = calculate_percentage(420, 500)
print(f"[SELF-TEST] 420/500 = {test_pct}% -> Grade: {assign_letter_grade(test_pct)}")
# Importing our custom user-defined module!
import grade_calculator as gc
student_name = "Priya Sharma"
obtained_marks = 445
maximum_marks = 500
# Calling functions defined inside grade_calculator module
pct = gc.calculate_percentage(obtained_marks, maximum_marks)
grade = gc.assign_letter_grade(pct)
print(f"Student Name : {student_name}")
print(f"Marks Scored : {obtained_marks}/{maximum_marks}")
print(f"Percentage : {pct}%")
print(f"Final Grade : {grade}")
print(f"Pass Cutoff : {gc.PASSING_PERCENTAGE}%")
A package is a directory on the file system that contains multiple Python modules and a special file named __init__.py. Packages allow multi-level hierarchical structuring using dot notation (e.g. import college.admissions.forms).
__init__.py executes automatically the instant the package is imported.__all__): You can define __all__ = ["admissions", "examinations"] inside __init__.py to control exactly what gets imported when someone writes from package import *.# Style 1: Import full module path
import university_portal.examinations as exams
exams.publish_results("BCA Sem 1")
# Style 2: Import specific submodule function directly
from university_portal.finance.fee_billing import generate_receipt
receipt_id = generate_receipt(student_id=1082, amount=25000)
print("Generated Receipt ID:", receipt_id)
pip stands for "Pip Installs Packages". It is the official package management system for Python, pre-installed with modern Python distributions. PyPI (Python Package Index) is the official central cloud repository hosting over 500,000 free, open-source Python packages created by software developers worldwide (such as requests for internet APIs, pandas for data analysis, and flask for web development).
pip install requests in PowerShell or Command Prompt.site-packages.| Command | What It Does | Real Example |
|---|---|---|
pip install <pkg> |
Downloads and installs the latest version of a package. | pip install requests |
pip install <pkg>==<ver> |
Installs an exact specific version of a package. | pip install flask==2.3.0 |
pip list |
Displays all packages currently installed in the environment. | pip list |
pip show <pkg> |
Shows detailed metadata: author, version, license, location. | pip show requests |
pip uninstall <pkg> |
Cleanly removes an installed package. | pip uninstall requests |
pip freeze > requirements.txt |
Exports an exact list of all project dependencies to a text file. | pip freeze > requirements.txt |
pip install -r requirements.txt |
Installs all packages listed in a requirements file in one command! | pip install -r requirements.txt |
A Virtual Environment is an isolated, self-contained directory tree that contains its own Python interpreter and independent set of libraries. Packages installed inside a virtual environment do not interfere with other virtual environments or with the global system Python installation.
env_proj_a/ contains Django 3.2.env_proj_b/ contains Django 5.0.python -m venv myenv
myenv/ containing a private Python copy).
.\myenv\Scripts\Activate.ps1
myenv\Scripts\activate.bat
source myenv/bin/activate
(myenv) at the beginning).
pip install requests flask
deactivate
This capstone demonstrates how clean modular code works in production: using math, random, datetime, and sys together inside an organized business logic module.
import math
import random
import datetime
import sys
def generate_order_id():
"""Generates a unique random order ID with current timestamp."""
timestamp = datetime.datetime.now().strftime("%Y%m%d")
random_suffix = random.randint(1000, 9999)
return f"ORD-{timestamp}-{random_suffix}"
def calculate_cart_total(item_prices, discount_rate=0.10, tax_rate=0.18):
"""Calculates gross total, applies discount, and adds GST using math functions."""
gross_amount = sum(item_prices)
discount_amount = gross_amount * discount_rate
discounted_subtotal = gross_amount - discount_amount
tax_amount = discounted_subtotal * tax_rate
# Using math.ceil to round up invoice cents
final_payable = math.ceil(discounted_subtotal + tax_amount)
return {
"order_id": generate_order_id(),
"gross": gross_amount,
"discount": round(discount_amount, 2),
"tax": round(tax_amount, 2),
"total": final_payable,
"created_at": datetime.datetime.now().strftime("%d-%b-%Y %I:%M %p")
}
# Execution demonstration
cart_items = [499.0, 1299.0, 249.50, 850.0]
invoice = calculate_cart_total(cart_items)
print("============================================")
print(f" INVOICE: {invoice['order_id']}")
print("============================================")
print(f" Date & Time : {invoice['created_at']}")
print(f" Items Count : {len(cart_items)}")
print(f" Gross Subtotal : ₹{invoice['gross']:.2f}")
print(f" Discount (10%) : -₹{invoice['discount']:.2f}")
print(f" GST Tax (18%) : +₹{invoice['tax']:.2f}")
print("--------------------------------------------")
print(f" FINAL PAYABLE : ₹{invoice['total']}")
print("============================================")
.py extension containing Python definitions (functions, classes, variables) and executable statements. The four major advantages are: (1) Code Reusability, (2) Namespace Isolation, (3) Maintainability, and (4) Team Collaboration.
math.py).__init__.py file, providing a hierarchical multi-level namespace (e.g. urllib.request).
__name__ variable to "__main__". When imported into another file, __name__ is set to the module's file name. This construct allows developers to include test blocks or scripts that execute only when the file is run directly, without running during imports.
sys.path is a list of directory strings where Python searches for modules. Python searches in this order: (1) In-memory sys.modules cache, (2) Built-in C modules, (3) Current working directory, (4) PYTHONPATH and Standard Library, (5) site-packages. If not found, it raises ModuleNotFoundError.
pip install -r requirements.txt to recreate the exact identical development environment.