Python 3 — Modules & Standard Library

🐍 Python 3 🟢 Lesson 11 📅 July 2026

A module is a Python file containing functions, classes, and variables that you can reuse in other programs. Python comes with a rich standard library of built-in modules for math, file handling, dates, networking, and much more — all ready to use without any installation.

1 Importing Modules
Python 3 — Import Syntax▶ Run Code
# Import entire module (access with module.function)
import math
print(math.sqrt(144))   # 12.0
print(math.pi)          # 3.14159...

# Import specific items (no prefix needed)
from math import sqrt, pi, factorial
print(sqrt(64))         # 8.0
print(pi)               # 3.14159...
print(factorial(5))     # 120

# Import with alias (rename for convenience)
import math as m
print(m.ceil(4.2))      # 5

from datetime import datetime as dt
print(dt.now())         # Current date and time
2 The math Module
Python 3 — math Module▶ Run Code
import math

# Constants
print(math.pi)          # 3.141592653589793
print(math.e)           # 2.718281828459045
print(math.inf)         # inf
print(math.nan)         # nan

# Rounding
print(math.ceil(4.1))   # 5 (always rounds up)
print(math.floor(4.9))  # 4 (always rounds down)
print(round(4.5))       # 4 (banker's rounding)
print(round(4.567, 2))  # 4.57

# Powers & roots
print(math.sqrt(256))   # 16.0
print(math.pow(2, 10))  # 1024.0
print(math.log(100, 10))# 2.0 — log base 10

# Trigonometry
angle = math.radians(90)  # Convert degrees to radians
print(math.sin(angle))    # 1.0
print(math.cos(angle))    # ~0 (very small float)

# Number theory
print(math.gcd(48, 18))  # 6
print(math.lcm(4, 6))    # 12 (Python 3.9+)
3 The random Module
Python 3 — random Module▶ Run Code
import random

# Random float between 0 and 1
print(random.random())           # e.g., 0.7482...

# Random integer in range (inclusive)
print(random.randint(1, 6))      # Dice roll: 1-6

# Random float in range
print(random.uniform(10.0, 20.0)) # e.g., 14.573...

# Choose random item from list
fruits = ["apple", "banana", "cherry", "mango"]
print(random.choice(fruits))     # e.g., "cherry"

# Shuffle a list in place
cards = list(range(1, 14))       # 1 to 13
random.shuffle(cards)
print(cards)                     # Shuffled

# Pick multiple unique items
winners = random.sample(range(1, 101), 3)  # 3 lottery numbers
print(f"Winners: {winners}")

# Seed for reproducible results
random.seed(42)
print(random.randint(1, 100))   # Always same with seed 42
4 The datetime Module
Python 3 — datetime Module▶ Run Code
from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
print(now)                           # e.g., 2026-07-22 12:30:45.123
print(now.year, now.month, now.day)  # 2026 7 22
print(now.hour, now.minute)          # 12 30

# Format date as string
formatted = now.strftime("%d %B %Y, %I:%M %p")
print(formatted)  # e.g., "22 July 2026, 12:30 PM"

# Parse string to datetime
birthday = datetime.strptime("1999-05-15", "%Y-%m-%d")
print(birthday)

# Date arithmetic with timedelta
today = date.today()
one_week = timedelta(days=7)
next_week = today + one_week
print(f"Next week: {next_week}")

# Calculate age
birth = date(1999, 5, 15)
age = (date.today() - birth).days // 365
print(f"Age: {age} years")
5 The os Module
Python 3 — os Module▶ Run Code
import os

# Current working directory
print(os.getcwd())

# List files in directory
files = os.listdir(".")
print(files[:5])  # First 5 files

# Join paths (cross-platform safe)
home = os.path.expanduser("~")
docs = os.path.join(home, "Documents", "python_notes.txt")
print(docs)

# Path operations
filepath = "/home/balaji/projects/script.py"
print(os.path.dirname(filepath))   # /home/balaji/projects
print(os.path.basename(filepath))  # script.py
print(os.path.exists(filepath))    # True/False
print(os.path.splitext(filepath))  # ('/home/.../script', '.py')

# Environment variables
path = os.environ.get("PATH", "Not found")
print(path[:50] + "...")
6 The sys Module
Python 3 — sys Module▶ Run Code
import sys

# Python version info
print(sys.version)
print(sys.version_info.major)  # 3

# Platform
print(sys.platform)   # 'win32', 'linux', 'darwin'

# Exit program (don't run in tutorial, just FYI)
# sys.exit(0)   # 0 = success, 1 = error

# Command line arguments
print(sys.argv)  # ['script.py', 'arg1', 'arg2']

# Maximum integer
print(sys.maxsize)     # 9223372036854775807

# Module search path
print(sys.path[:3])   # First 3 directories Python searches
7 Creating Custom Modules

Any Python file (.py) can be a module. Save functions in a file and import them in another:

Python 3 — Custom Module▶ Run Code
# Imagine this is in "mymath.py":
# ─────────────────────────────────
# def add(a, b): return a + b
# def subtract(a, b): return a - b
# def average(*nums): return sum(nums) / len(nums)
# PI = 3.14159
# ─────────────────────────────────

# In another file, you'd import it:
# import mymath
# print(mymath.add(5, 3))      # 8
# print(mymath.PI)             # 3.14159
# print(mymath.average(1,2,3,4,5))  # 3.0

# The __name__ guard: code only runs when file is executed directly
# def main():
#     print("Running mymath directly!")
# if __name__ == "__main__":
#     main()

# Without this guard, code would also run when imported!

# For now, demonstrate with collections module
from collections import Counter, defaultdict
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
count = Counter(words)
print(count)                  # Counter({'apple': 3, ...})
print(count.most_common(2))   # [('apple', 3), ('banana', 2)]
8 Coding Challenge

Write a program that uses multiple modules to:

  • Generate 10 random lottery numbers (1-50, no repeats) using random.sample()
  • Calculate statistics (min, max, sum, average) using math
  • Display the current date using datetime in format "DD Month YYYY"
  • Check how many days until a future date (e.g., New Year) using timedelta
  • Print the Python version and platform using sys