Modules and Packages

Reviewed & published by Brayan K

Organize your code, reuse functionality, and explore Python's powerful built-in libraries.

Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.

What You'll Learn in This Lesson

What Are Modules?

A module is simply a Python file (.py) that contains code you can reuse. Instead of writing everything in one file, you split your code into organized pieces.

TermWhat It IsExample
ModuleA single .py filemath.py, helpers.py
PackageA folder of modulesmy_app/ folder
LibraryCollection of packagesrequests, numpy

Why Use Modules?

BenefitDescription
ReusabilityWrite once, use everywhere
OrganizationKeep related code together
MaintainabilityEasier to find and fix bugs
CollaborationTeams can work on different files

Importing Modules

Use the import keyword to use a module:

StyleSyntaxUsage
Import whole moduleimport mathmath.sqrt(16)
Import specific itemfrom math import sqrtsqrt(16)
Import with aliasimport math as mm.sqrt(16)
Import multiplefrom math import sqrt, pisqrt(16), pi
# Different ways to import
import math
print("Using import math:")
print(f"  math.sqrt(25) = {math.sqrt(25)}")
print(f"  math.pi = {math.pi:.4f}")

from math import sqrt, ceil
print("\nUsing from math import sqrt, ceil:")
print(f"  sqrt(49) = {sqrt(49)}")
print(f"  ceil(4.2) = {ceil(4.2)}")

import datetime as dt
print("\nUsing import datetime as dt:")
print(f"  1 January 2026 was a {dt.date(2026, 1, 1):%A}")

# ✅ Expected output:
# Using import math:
#   math.sqrt(25) = 5.0
#   math.pi = 3.1416
#
# Using from math import sqrt, ceil:
#   sqrt(49) = 7.0
#   ceil(4.2) = 5
#
# Using import datetime as dt:
#   1 January 2026 was a Thursday

Worked Example: The Import Styles Side by Side

Here is one small program that uses three of those import styles at once. Read it line by line — every line says what it prints and why that style was chosen. Then run it and check your reading against the real output.

import math                     # Style 1: the whole module. You keep the "math." prefix.
from math import sqrt, floor    # Style 2: copy just two names into THIS file.
import statistics as stats      # Style 3: same module, shorter local name (an alias).

readings = [4.0, 9.0, 16.0, 25.0]

# Style 1 — the prefix tells a reader exactly where hypot() came from.
print("hypot(3, 4) =", math.hypot(3, 4))       # 5.0  (the long side of a 3-4-5 triangle)

# Style 2 — no prefix needed, because sqrt now lives in your own namespace.
# "Namespace" just means the set of names your file can see.
roots = [sqrt(r) for r in readings]
print("roots       =", roots)                  # [2.0, 3.0, 4.0, 5.0]

# floor() cuts a decimal DOWN to the nearest whole number - it never rounds up.
print("floor(3.9)  =", floor(3.9))             # 3

# Style 3 — the alias 'stats' IS the statistics module from here on.
print("mean        =", stats.mean(readings))   # 13.5

# A module is just an object holding names. dir() lists them, which is handy
# when you half-remember a function name.
print("has sqrt?   =", "sqrt" in dir(math))    # True

# ✅ Expected output:
# hypot(3, 4) = 5.0
# roots       = [2.0, 3.0, 4.0, 5.0]
# floor(3.9)  = 3
# mean        = 13.5
# has sqrt?   = True

🎯 Your Turn: Write the Import Lines

The body of this program is already written. Only the three import lines are missing — one of each style. Fill in each ___, run it, and check it against the expected output in the comment at the bottom.

# 🎯 YOUR TURN — replace each ___ so the program runs.

___ math                        # 👉 import the WHOLE math module (style 1)
from random import ___, seed    # 👉 you need randint below; seed is already listed for you
import datetime as ___          # 👉 give datetime the short alias dt (style 3)

seed(7)   # Fixes the random number generator so everyone gets the SAME roll.

roll = randint(1, 6)                    # a whole number from 1 to 6, both included
print("dice roll:", roll)

print("circle area (r=3):", round(math.pi * 3 ** 2, 2))   # pi x radius squared

print("1 Jan 2026 is a", dt.date(2026, 1, 1).strftime("%A"))   # %A = weekday name

# ✅ Expected output:
# dice roll: 3
# circle area (r=3): 28.27
# 1 Jan 2026 is a Thursday

The math Module

Python's built-in math module provides mathematical functions:

FunctionWhat It DoesExample
math.sqrt(x)Square rootsqrt(16) → 4.0
math.ceil(x)Round upceil(4.2) → 5
math.floor(x)Round downfloor(4.8) → 4
math.pow(x, y)x to the power of ypow(2, 3) → 8.0
math.piPi constant3.14159...
import math

print("=== Math Module ===")
print(f"Square root of 64: {math.sqrt(64)}")
print(f"2 to the power of 10: {math.pow(2, 10)}")
print(f"Ceiling of 3.2: {math.ceil(3.2)}")
print(f"Floor of 3.8: {math.floor(3.8)}")
print(f"Pi: {math.pi:.6f}")
print(f"Factorial of 5: {math.factorial(5)}")

# ✅ Expected output:
# === Math Module ===
# Square root of 64: 8.0
# 2 to the power of 10: 1024.0
# Ceiling of 3.2: 4
# Floor of 3.8: 3
# Pi: 3.141593
# Factorial of 5: 120

The random Module

Generate random numbers for games, testing, or simulations:

FunctionWhat It Does
random.randint(a, b)Random integer from a to b (inclusive)
random.random()Random float between 0 and 1
random.choice(list)Pick one random item
random.shuffle(list)Shuffle list in place
random.sample(list, n)Pick n random items
import random

print("=== Random Module ===")
print(f"Random number 1-100: {random.randint(1, 100)}")
print(f"Random decimal: {random.random():.4f}")

colors = ["red", "blue", "green", "yellow"]
print(f"Random color: {random.choice(colors)}")

numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled: {numbers}")

print(f"Pick 2 colors: {random.sample(colors, 2)}")

The datetime Module

Work with dates and times:

from datetime import datetime, date, timedelta

# Current date and time
now = datetime.now()
print("=== Datetime Module ===")
print(f"Now: {now}")
print(f"Date only: {date.today()}")
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")

# Formatting dates
print(f"\nFormatted: {now.strftime('%B %d, %Y')}")
print(f"Time: {now.strftime('%H:%M:%S')}")

# Date math
tomorrow = date.today() + timedelta(days=1)
next_week = date.today() + timedelta(weeks=1)
print(f"\nTomorrow: {tomorrow}")
print(f"Next week: {next_week}")

The os Module

Interact with your computer's operating system:

import os

print("=== OS Module ===")
print(f"Current directory: {os.getcwd()}")
print(f"Operating system: {os.name}")

# Path operations (works on any OS)
path = os.path.join("folder", "subfolder", "file.txt")
print(f"\nJoined path: {path}")
print(f"File name: {os.path.basename(path)}")
print(f"Directory: {os.path.dirname(path)}")

# Check if path exists
print(f"\nCurrent dir exists: {os.path.exists('.')}")

The json Module

JSON (JavaScript Object Notation) is a universal format for storing and exchanging data. It's used by almost every API.

FunctionWhat It Does
json.dumps(obj)Convert Python → JSON string
json.loads(string)Convert JSON string → Python
json.dump(obj, file)Write Python to JSON file
json.load(file)Read JSON file to Python
import json

# Python dictionary
user = {
    "name": "Alice",
    "age": 25,
    "is_student": True,
    "skills": ["Python", "JavaScript"]
}

# Convert to JSON string
json_string = json.dumps(user, indent=2)
print("=== Python to JSON ===")
print(json_string)

# Convert back to Python
parsed = json.loads(json_string)
print(f"\n=== Back to Python ===")
print(f"Name: {parsed['name']}")
print(f"Skills: {parsed['skills']}")

# ✅ Expected output:
# === Python to JSON ===
# {
#   "name": "Alice",
#   "age": 25,
#   "is_student": true,
#   "skills": [
#     "Python",
#     "JavaScript"
#   ]
# }
#
# === Back to Python ===
# Name: Alice
# Skills: ['Python', 'JavaScript']

Creating Your Own Module

Any Python file can be a module. Just save your code and import it:

Step 1: Create helpers.py

# helpers.py
def greet(name):
    return f"Hello, {name}!"

def add(a, b):
    return a + b

Step 2: Import in another file

# main.py
import helpers

print(helpers.greet("World"))
print(helpers.add(5, 3))
# Simulating a custom module

# This would be in my_helpers.py:
def greet(name):
    return f"Hello, {name}!"

def calculate_area(length, width):
    return length * width

PI = 3.14159

# Using the "module":
print(greet("Python Learner"))
print(f"Area: {calculate_area(5, 3)}")
print(f"PI value: {PI}")

# ✅ Expected output:
# Hello, Python Learner!
# Area: 15
# PI value: 3.14159

Understanding Packages

A package is a folder containing multiple modules. It must have an __init__.py file (can be empty).

my_package/
    __init__.py      ← Makes it a package
    greetings.py     ← Module 1
    math_utils.py    ← Module 2
    helpers.py       ← Module 3
from my_package import greetings
from my_package.math_utils import calculate
import my_package.helpers as h

Installing External Packages with pip

pip is Python's package manager. It downloads packages from PyPI (Python Package Index) — a library of over 400,000 packages!

CommandWhat It Does
pip install requestsInstall a package
pip uninstall requestsRemove a package
pip listShow installed packages
pip freezeList packages with versions

Popular packages to try:

Common Mistakes to Avoid

MistakeProblemFix
from math import *Can overwrite your variablesfrom math import sqrt
Naming file same as modulemath.py shadows built-in mathUse unique file names
Circular importsA imports B, B imports ARestructure your code
Forgetting __init__.pyFolder not recognized as packageAdd empty __init__.py

Practical Example: Password Generator

Use multiple modules to create a random password generator:

import random
import string

def generate_password(length=12):
    """Generate a secure random password."""
    # All possible characters
    characters = string.ascii_letters + string.digits + "!@#$%"
    
    # Generate password
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

# Generate passwords of different lengths
print("=== Password Generator ===")
print(f"8 chars:  {generate_password(8)}")
print(f"12 chars: {generate_password(12)}")
print(f"16 chars: {generate_password(16)}")

Practical Example: Date Calculator

Calculate days between dates and future dates:

from datetime import datetime, date, timedelta

def days_until(target_date, today=None):
    """Days from today (or the day you pass in) until a target date."""
    today = today or date.today()
    target = datetime.strptime(target_date, "%Y-%m-%d").date()
    delta = target - today
    return delta.days

def add_days(start_date, days):
    """Add days to a date."""
    start = datetime.strptime(start_date, "%Y-%m-%d").date()
    result = start + timedelta(days=days)
    return result.strftime("%B %d, %Y")

# Examples. days_until() counts from the real today unless you pass a day,
# so pinning one here gives the same answer whenever you run it.
print("=== Date Calculator ===")
print(f"Days from 2026-01-01 until 2026-12-31: {days_until('2026-12-31', date(2026, 1, 1))}")
print(f"30 days from 2025-01-01: {add_days('2025-01-01', 30)}")

# ✅ Expected output:
# === Date Calculator ===
# Days from 2026-01-01 until 2026-12-31: 364
# 30 days from 2025-01-01: January 31, 2025

Practical Example: Data Analyzer

Use json and math to analyze data:

import json
import math

# Sample data (could come from a file or API)
data_json = '''
{
    "students": [
        {"name": "Alice", "score": 85},
        {"name": "Bob", "score": 92},
        {"name": "Charlie", "score": 78},
        {"name": "Diana", "score": 95}
    ]
}
'''

# Parse JSON
data = json.loads(data_json)
scores = [s["score"] for s in data["students"]]

# Calculate statistics
average = sum(scores) / len(scores)
highest = max(scores)
lowest = min(scores)

print("=== Student Score Analysis ===")
print(f"Students: {len(scores)}")
print(f"Average: {average:.1f}")
print(f"Highest: {highest}")
print(f"Lowest: {lowest}")
print(f"Range: {highest - lowest}")

# ✅ Expected output:
# === Student Score Analysis ===
# Students: 4
# Average: 87.5
# Highest: 95
# Lowest: 78
# Range: 17

🎯 Mini-Challenge: Build Your Own Mini-Module

Time to write one with no code pre-filled. Treat the block below as a file called temps.py — a tiny module of temperature helpers that another program could import. Only the brief is given; the code is yours.

# 🎯 MINI-CHALLENGE: temps.py — your own mini-module
#
# 1. Import the statistics module (whole module, keep the prefix).
# 2. Create a constant list:
#        READINGS = [12.5, 18.0, 21.5, 9.0, 15.0]      # degrees Celsius
# 3. Write to_fahrenheit(c) that returns  c * 9 / 5 + 32
# 4. Write summary(readings) that returns a dictionary with three keys:
#        "count"  -> how many readings there are
#        "mean_c" -> statistics.mean of the readings, rounded to 1 decimal place
#        "max_f"  -> the HIGHEST reading converted to Fahrenheit, rounded to 1 dp
# 5. Print summary(READINGS)
#
# ✅ Expected output:
# {'count': 5, 'mean_c': 15.2, 'max_f': 70.7}

# your code here

Summary: Quick Reference

ConceptDescriptionExample
import xImport whole moduleimport math
from x import yImport specific itemfrom math import sqrt
import x as yImport with aliasimport pandas as pd
pip install xInstall packagepip install requests

Key Built-in Modules:

Wrapping Up

You now know how to organize your code into reusable modules, use Python's powerful standard library, and install external packages. This is how professional developers work!

🏅 Intermediate Track Complete! You now code like a real developer!

Functions, Lists, Dictionaries, File Handling, Exceptions, Modules — you've completed all 11 beginner and intermediate lessons. You now have the full Python toolkit that powers real applications.

Practice quiz

What is a module in Python?

  • A folder of files
  • A function inside a class
  • A single .py file containing reusable code
  • An installed library only

Answer: A single .py file containing reusable code. A module is simply a Python (.py) file whose code you can import and reuse.

Which import lets you call sqrt(16) directly (without a prefix)?

  • from math import sqrt
  • import math
  • import math as m
  • import sqrt

Answer: from math import sqrt. from math import sqrt brings sqrt into your namespace so you call it without math..

After 'import math as m', how do you compute a square root?

  • math.sqrt(16)
  • sqrt(16)
  • m(sqrt(16))
  • m.sqrt(16)

Answer: m.sqrt(16). The alias m replaces the module name, so use m.sqrt(16).

What does math.ceil(4.2) return?

  • 4
  • 5
  • 4.2
  • 4.0

Answer: 5. math.ceil rounds UP to the next integer, so ceil(4.2) is 5.

What does math.floor(4.8) return?

  • 4
  • 5
  • 4.8
  • 5.0

Answer: 4. math.floor rounds DOWN, so floor(4.8) is 4.

Which random function picks one random item from a list?

  • random.randint(list)
  • random.shuffle(list)
  • random.choice(list)
  • random.pick(list)

Answer: random.choice(list). random.choice(list) returns a single randomly selected item.

What does random.shuffle(my_list) do?

  • Returns a new shuffled list
  • Shuffles the list in place and returns None
  • Picks one item
  • Sorts the list

Answer: Shuffles the list in place and returns None. random.shuffle reorders the list in place; it does not return a new list.

Why is 'from math import *' discouraged?

  • It is slower
  • It only imports pi
  • It is a syntax error
  • It can overwrite your own variables / cause naming conflicts

Answer: It can overwrite your own variables / cause naming conflicts. Star imports dump every name in, which can shadow your variables and cause conflicts.

What file makes a folder into a package?

  • __main__.py
  • __init__.py
  • setup.py
  • package.py

Answer: __init__.py. A folder needs an __init__.py file (it can be empty) to be treated as a package.

What is pip?

  • A built-in math module
  • A way to run scripts
  • Python's package manager for installing packages from PyPI
  • A type of loop

Answer: Python's package manager for installing packages from PyPI. pip installs external packages from PyPI, e.g. pip install requests.

Continue this course