PyPython · Lesson 6 of 14

Modules & Packages

Python's standard library is enormous. And if that's not enough, there's PyPI with 500,000+ packages. You will rarely need to write code from scratch.

A module is just a Python file. You can import any module using the import keyword, and access its contents with dot notation. The standard library covers math, dates, files, networking, JSON, and much more.

Python
import math
import random
import os
from datetime import datetime

# math module
print(math.pi)              # 3.141592653589793
print(math.sqrt(16))        # 4.0
print(math.ceil(3.2))       # 4
print(math.floor(3.9))      # 3

# random module
print(random.randint(1, 10))        # random int 1-10
print(random.choice(["a","b","c"])) # random element
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)              # shuffle in-place

# datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M"))  # 2024-01-15 14:30

# os module
print(os.getcwd())               # current directory
files = os.listdir(".")          # list files
os.makedirs("new_dir", exist_ok=True)  # create directory

Write your own module by creating a .py file. Import it by filename (without .py). Use pip to install third-party packages from PyPI.

Python
# mymath.py
def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

PI = 3.14159

# In another file:
# import mymath
# print(mymath.add(2, 3))     # 5
# print(mymath.PI)             # 3.14159

# Or import specific names:
# from mymath import add, PI
# print(add(2, 3))             # 5

# Installing packages with pip
# pip install requests         (HTTP client)
# pip install pandas           (data manipulation)
# pip install flask            (web framework)

# Virtual environments — isolate dependencies per project
# python3 -m venv venv         (create)
# source venv/bin/activate     (activate on Mac/Linux)
# venv\Scripts\activate       (activate on Windows)
# pip install requests         (installs into venv, not system)
◆ Note
Always use a virtual environment for projects. Without one, pip installs packages globally and you'll eventually hit version conflicts. It's two extra commands and will save you hours of pain.