Python Basics - 05. Modules and Packages

To avoid writing everything from scratch and to organize code into separate files, Python uses Modules and Packages. This notebook will show you how to import them and utilize Python’s rich standard library.

Download Notebook

Download this notebook

1. Importing Modules

A module can simply be another Python file containing functions, classes, or variables. You load a module’s contents into your current file using the import statement.

import math

print(f"Value of Pi: {math.pi}")
print(f"Square root of 16: {math.sqrt(16)}")

# You can also give the module an alias, which is very common with big libraries (e.g. import pandas as pd)
import datetime as dt

current_date = dt.date.today()
print(f"Today's Date: {current_date}")
Value of Pi: 3.141592653589793
Square root of 16: 4.0
Today's Date: 2026-03-06

2. Importing Specific Items (from … import …)

If you only need a specific function or variable from a module, you can import it directly. This removes the need to prefix the item with the module name.

from random import randint, choice

# Notice we don't need 'random.randint()', just 'randint()'
print(f"Random integer between 1 and 10: {randint(1, 10)}")
print(f"Random choice from a list: {choice(['Apple', 'Banana', 'Cherry'])}")
Random integer between 1 and 10: 8
Random choice from a list: Banana

3. The Python Standard Library Overview

Python comes with “batteries included”, meaning it has a huge standard library covering network access, system interactions, text processing, and more.

  • os: Interfaces with the underlying operating system

  • sys: Accesses system-specific parameters and functions

  • json: A lightweight data interchange format popular on the web

import os
import sys
import json

print(f"Current Working Directory (CWD): {os.getcwd()}")
print(f"Current Python Version: {sys.version.split(' ')[0]}")

# Converting a Python Dictionary into a JSON formatted string
python_dict = {"name": "Alice", "role": "Developer", "skills": ["Python", "SQL"]}
json_string = json.dumps(python_dict, indent=4)  # indent=4 makes it readable

print("\nSerialized JSON:")
print(json_string)
Current Working Directory (CWD): /home/runner/work/docs.post/docs.post/source/prog/python
Current Python Version: 3.12.13

Serialized JSON:
{
    "name": "Alice",
    "role": "Developer",
    "skills": [
        "Python",
        "SQL"
    ]
}

4. Writing and Importing Your Own Module

The core idea is simple:

  1. Define functions in one file (for example, my_math.py).

  2. Import and use them in another file (for example, main.py).

This is the most common module workflow in Python projects.

# Step 1: Create module file: my_math.py
from pathlib import Path

Path("my_math.py").write_text(
    "def add(a, b):\n"
    "    return a + b\n\n"
    "def multiply(a, b):\n"
    "    return a * b\n"
)

# Step 2: Create caller file: main.py
Path("main.py").write_text(
    "from my_math import add, multiply\n\n"
    "print(add(2, 3))\n"
    "print(multiply(4, 5))\n"
)

# Step 3: Run main.py to use functions from my_math.py
exec(Path("main.py").read_text())
5
20