Lesson 6 of 34 · 0 of 2 exercises solved

Modules & Packages

let you split code across files and reuse code other people have written. Python ships with a large , and PyPI hosts hundreds of thousands of extra .

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, , and much more.

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
Python (loads on first run)Ctrl+Enter runs

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

# 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)
Python (loads on first run)Ctrl+Enter runs

Common question

Does importing a module run its code?

A module is a file of Python code. The first import finds the file on sys.path, runs it to build a module object, stores that object in sys.modules, and binds a name to it. Later imports reuse the cached object, so a module's top-level code runs exactly once per program. Everything the module defined (, classes, constants) is then reachable with a dot.

This shapes good style. Keep the top level to definitions and constants so importing is cheap and predictable. Prefer import math or from math import sqrt over star imports. Put script behaviour under the main check. And remember your own files are modules too: a file called tools.py in the same folder is one import tools away.

Source: The Python import system docs: "The import statement combines two operations: it searches for the named module, then it binds the results of that search to a name in the local ." Loading the module includes running it.

Common mix-ups

Each of these sounds reasonable. Think about why it is wrong, then open the explanation.

  • import just declares a name, like a header file in C, and runs no code.

  • from math import * is best because it saves typing.

  • The if __name__ == "__main__" check is boilerplate that does nothing.

Practice

Import the math module and write hypotenuse(a, b) that returns the length of the long side of a right triangle. math.sqrt or math.hypot both work.

Exercise

Borrow from the standard library

3 checks
# import what you need

def hypotenuse(a, b):
    ...


print(hypotenuse(3, 4))
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Use the datetime module to write days_between(start, end) that takes two ISO date such as "2026-01-01" and returns the number of days from the first to the second.

Exercise

Counting days

3 checks
from datetime import date

def days_between(start, end):
    # date.fromisoformat(...) turns a string into a date
    ...


print(days_between("2026-01-01", "2026-12-25"))
 
Python (loads on first run)Ctrl+Enter runs
Output
Press Run to try your code, then Check answer to grade it.

Check yourself

Quick check

Why do Python scripts often end with if __name__ == "__main__": main()?

Finished reading?2 exercises still open. You can come back to them later.

Tip: use the ← and → keys to move between lessons.