A module is a file containing Python code (functions, classes, variables) that can be imported and reused in other Python files.
Why use modules?
- Reusability — write once, use anywhere
- Organization — break large programs into smaller files
- Namespace — avoid naming conflicts
- Maintainability — easier to manage separate concerns
Any .py file is a module. You create one simply by writing Python code in a file.
# File: math_utils.py ← this IS a module
PI = 3.14159265358979
def add(a, b):
"""Return sum of a and b."""
return a + b
def subtract(a, b):
"""Return difference of a and b."""
return a - b
def multiply(a, b):
"""Return product of a and b."""
return a * b
def divide(a, b):
"""Return division of a and b."""
if b == 0:
raise ZeroDivisionError("Cannot divide by zero")
return a / b
def circle_area(radius):
"""Return area of a circle."""
return PI * radius ** 2
class Calculator:
"""A simple calculator class."""
def __init__(self, initial=0):
self.result = initial
def add(self, n):
self.result += n
return self
def subtract(self, n):
self.result -= n
return self
def get_result(self):
return self.result# ──────────────────────────────────────────────
# File: main.py (in the same directory as math_utils.py)
# ──────────────────────────────────────────────
# Method 1: import the entire module
import math_utils
print(math_utils.PI) # 3.14159265358979
print(math_utils.add(5, 3)) # 8
print(math_utils.circle_area(7)) # 153.93804...
# Method 2: import specific names — brings them into local namespace
from math_utils import add, subtract, PI
print(add(10, 5)) # 15 — no need for module prefix
print(PI) # 3.14159...
# Method 3: import with alias
import math_utils as mu
print(mu.add(4, 6)) # 10 — shorter prefix
from math_utils import circle_area as area
print(area(5)) # 78.539...
# Method 4: import everything (AVOID — pollutes namespace!)
from math_utils import *
print(add(1, 2)) # works, but unclear where it comes from
# This makes code hard to read — avoid in production code
# Checking what's in a module
print(dir(math_utils)) # list all names in the module
help(math_utils) # full documentation
help(math_utils.add) # help on specific function# File: math_utils.py
def add(a, b):
return a + b
# This block runs ONLY when the file is executed directly,
# NOT when it's imported as a module!
if __name__ == "__main__":
# Test code / demo code / entry point
print("Testing math_utils module...")
print(add(5, 3)) # 8
print(add(10, -2)) # 8
# When you run: python math_utils.py
# → __name__ == "__main__" is True → block runs
# When you do: import math_utils
# → __name__ == "math_utils" (the module name) → block does NOT runPython has a massive standard library. Here are the most important ones:
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sqrt(16)) # 4.0
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
print(math.factorial(5)) # 120
print(math.log(100, 10)) # 2.0 (log base 10)
print(math.log2(8)) # 3.0
print(math.sin(math.pi/2)) # 1.0
print(math.pow(2, 10)) # 1024.0
print(math.gcd(48, 18)) # 6
print(math.inf) # infinity
print(math.isnan(float('nan'))) # Trueimport random
print(random.random()) # float between 0 and 1
print(random.randint(1, 10)) # int between 1 and 10 (inclusive)
print(random.uniform(1.5, 10.5)) # float between 1.5 and 10.5
print(random.randrange(0, 100, 5)) # random from 0,5,10,...,95
items = ["apple", "banana", "cherry"]
print(random.choice(items)) # one random item
print(random.choices(items, k=5)) # 5 items with replacement
print(random.sample(items, k=2)) # 2 items WITHOUT replacement
random.shuffle(items) # shuffle in place
print(items)
random.seed(42) # reproducible results
print(random.random()) # always same output with same seedimport os
print(os.getcwd()) # current working directory
os.chdir("/path/to/dir") # change directory
print(os.listdir(".")) # list directory contents
os.mkdir("new_folder") # create directory
os.makedirs("a/b/c", exist_ok=True) # create nested dirs
os.rmdir("new_folder") # remove empty directory
os.remove("file.txt") # delete a file
os.rename("old.txt", "new.txt") # rename file
print(os.path.exists("file.txt")) # check if path exists
print(os.path.isfile("file.txt")) # is it a file?
print(os.path.isdir("folder")) # is it a directory?
print(os.path.join("home", "user", "docs")) # OS-safe path joining
print(os.path.basename("/home/user/file.txt")) # file.txt
print(os.path.dirname("/home/user/file.txt")) # /home/user
print(os.path.splitext("file.txt")) # ('file', '.txt')
print(os.path.getsize("file.txt")) # size in bytes
# Environment variables
print(os.environ.get("PATH"))
os.environ["MY_VAR"] = "hello"
print(os.getenv("MY_VAR", "default"))import sys
print(sys.version) # Python version string
print(sys.platform) # 'win32', 'linux', 'darwin'
print(sys.argv) # command line arguments
print(sys.path) # Python module search paths
print(sys.maxsize) # max int value
sys.exit(0) # exit program (0 = success)
sys.exit(1) # exit with error
# Redirect stdout
import io
old_stdout = sys.stdout
sys.stdout = io.StringIO() # capture print output
print("captured")
output = sys.stdout.getvalue()
sys.stdout = old_stdout
print(f"Got: {output}")from datetime import datetime, date, time, timedelta
# Current date/time
now = datetime.now()
today = date.today()
print(now) # 2024-01-15 14:30:45.123456
print(today) # 2024-01-15
# Creating datetime objects
dt = datetime(2024, 12, 25, 10, 30, 0)
print(dt.year, dt.month, dt.day) # 2024 12 25
print(dt.hour, dt.minute) # 10 30
# Formatting dates
print(now.strftime("%Y-%m-%d")) # 2024-01-15
print(now.strftime("%d/%m/%Y %H:%M:%S")) # 15/01/2024 14:30:45
print(now.strftime("%A, %B %d, %Y")) # Monday, January 15, 2024
# Parsing dates
dt = datetime.strptime("25-12-2024", "%d-%m-%Y")
print(dt) # 2024-12-25 00:00:00
# Arithmetic with timedelta
tomorrow = today + timedelta(days=1)
next_week = today + timedelta(weeks=1)
two_hours_ago = now - timedelta(hours=2)
diff = datetime(2024, 12, 31) - datetime.now()
print(f"Days until New Year: {diff.days}")import json
# Python dict → JSON string
data = {"name": "Logesh", "age": 25, "skills": ["Python", "JavaScript"]}
json_string = json.dumps(data)
print(json_string) # {"name": "Logesh", "age": 25, ...}
# Pretty formatted
json_pretty = json.dumps(data, indent=4)
print(json_pretty)
# JSON string → Python dict
json_str = '{"name": "Alice", "age": 30}'
python_dict = json.loads(json_str)
print(python_dict["name"]) # Alice
# File operations
with open("data.json", "w") as f:
json.dump(data, f, indent=4) # write to file
with open("data.json", "r") as f:
loaded = json.load(f) # read from file
print(loaded)from collections import Counter, defaultdict, OrderedDict, namedtuple, deque
# Counter — count occurrences
text = "mississippi"
counts = Counter(text)
print(counts) # Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
print(counts.most_common(2)) # [('i', 4), ('s', 4)]
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = Counter(words)
print(word_count.most_common(1)) # [('apple', 3)]
# defaultdict — dict with default values
dd = defaultdict(list)
dd["fruits"].append("apple")
dd["fruits"].append("banana")
dd["veggies"].append("carrot")
print(dict(dd)) # {'fruits': ['apple', 'banana'], 'veggies': ['carrot']}
dd_int = defaultdict(int)
for char in "hello world":
dd_int[char] += 1
# namedtuple — tuple with named fields
Point = namedtuple("Point", ["x", "y"])
Person = namedtuple("Person", ["name", "age", "city"])
p = Point(3, 4)
print(p.x, p.y) # 3 4
print(p[0], p[1]) # 3 4 — still indexable
person = Person("Logesh", 25, "Chennai")
print(person.name) # Logesh
# deque — double-ended queue (efficient append/popleft)
dq = deque([1, 2, 3, 4, 5])
dq.appendleft(0) # add to left → O(1)
dq.append(6) # add to right → O(1)
print(dq.popleft()) # 0 → O(1) (unlike list.pop(0) which is O(n))
dq.rotate(2) # rotate right by 2
print(list(dq))A package is a directory containing modules and an __init__.py file.
mypackage/
├── __init__.py ← marks this as a package
├── math_utils.py
├── string_utils.py
└── utils/
├── __init__.py
└── helpers.py
# mypackage/__init__.py
# Can be empty, or expose key items:
from .math_utils import add, subtract
from .string_utils import capitalize_words
# mypackage/math_utils.py
def add(a, b): return a + b
# mypackage/string_utils.py
def capitalize_words(text):
return " ".join(word.capitalize() for word in text.split())
# main.py
from mypackage import add, capitalize_words
import mypackage.math_utils as mu
print(add(5, 3)) # 8
print(capitalize_words("hello world")) # Hello World
print(mu.subtract(10, 4)) # 6Q: What is the difference between a module and a package?
A: A module is a single
.pyfile. A package is a directory of modules with an__init__.pyfile. Packages can contain sub-packages, forming a hierarchy. For example,numpyis a package;numpy.randomis a sub-package;numpy.random.randintis a function in that module.
Q: What does if __name__ == "__main__" do?
A:
__name__is a special variable. When a file is run directly,__name__equals"__main__". When it's imported,__name__equals the module's filename. This guard lets you include test/demo code in a module that only runs when executed directly, not when imported.
Q: What is the module search path?
A: When you
import something, Python searches in this order: (1) current directory, (2) directories inPYTHONPATHenvironment variable, (3) installation-dependent default (standard library, site-packages). You can inspect and modifysys.path.
| Concept | Key Point |
|---|---|
| Module | Any .py file |
import module |
Import whole module, use module.name |
from module import x |
Import specific names |
import module as alias |
Use shorter name |
from module import * |
Avoid — pollutes namespace |
__name__ |
"__main__" when run directly |
| Package | Directory with __init__.py |
sys.path |
Where Python looks for modules |
| Key modules | math, os, sys, datetime, json, random, collections |