Modules

A module is a Python file containing code you can import and reuse.

Importing Modules

import random

number = random.randint(1, 10)
print(number)

Import Specific Items

from random import randint, choice

number = randint(1, 10)
color = choice(["red", "blue", "green"])

Import with an Alias

import random as r

number = r.randint(1, 10)

Useful Standard Library Modules

These come built into Python:

random

import random

random.randint(1, 100)              # Random integer from 1 to 100
random.choice(["a", "b", "c"])      # Random item from list
random.shuffle(my_list)             # Shuffle list in place

csv

import csv

with open("data.csv", "r") as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)

json

import json

# String to dictionary
data = json.loads('{"name": "Alice"}')

# Dictionary to string
text = json.dumps({"name": "Alice"})

os

import os

os.path.exists("file.txt")    # Check if file exists
os.listdir(".")               # List files in directory

datetime

from datetime import datetime

now = datetime.now()
print(now.strftime("%Y-%m-%d"))

Installing External Packages

Beyond the standard library, you can install packages from PyPI (the Python Package Index) using a package manager. In this course we use uv. See the Packages and uv Guide for setup and usage.

Creating Your Own Modules

Any Python file can be imported as a module:

# helpers.py
def greet(name):
    return "Hello, " + name + "!"
# main.py
from helpers import greet

print(greet("Alice"))

Output:

Hello, Alice!

When your project has multiple files, use the __name__ guard and a main() function to keep things organized. See the Project Structure Guide for the full pattern.

Common Mistakes

Naming your file the same as a module

# If your file is named random.py:
import random  # Imports YOUR file, not the built-in module!

# Solution: rename your file to something else

Forgetting to install a package

import requests  # Error if not installed!

# Fix: uv add requests

Importing from the wrong location

# Wrong - helpers.py is in a different folder
from helpers import greet

# Right - specify the path
from utils.helpers import greet

Circular imports

# file_a.py
from file_b import something

# file_b.py
from file_a import something_else  # Error!

# Solution: restructure your code