New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› Python› Modules, Packages and Virtual Environments

Modules, Packages and Virtual Environments

💻 Python

Split code into modules, install packages and keep each project isolated.

Lesson 9 of 9 Tutorial
0 of 9 completed

Real programs are built from many files and third-party libraries. Modules keep that organized and virtual environments keep it clean.

By the end of this lesson you can:
  • Import modules and specific functions.
  • Create your own module.
  • Install packages in a virtual environment.

Importing

Python ships with a large standard library. Import a whole module or just the names you need.

import math
from datetime import date, timedelta

print(math.sqrt(81))          # 9.0
print(date.today())
print(date.today() + timedelta(days=7))

Your Own Module

Every .py file is a module. Create helpers.py with a function, then import it from main.py in the same folder.

# helpers.py
def slugify(text):
    return text.lower().strip().replace(" ", "-")

# main.py
from helpers import slugify

print(slugify("Introduction to Python"))

Virtual Environments

A virtual environment is a private folder of packages for one project. It prevents version clashes between projects.

python -m venv .venv
# Windows
.venv\Scripts\activate
# macOS / Linux
source .venv/bin/activate

pip install requests
pip freeze > requirements.txt

Using a Package

Once installed, import the package like any module. Keep a requirements.txt so another machine can install the same versions.

Warning Do not install packages globally for every project. Use a virtual environment each time.

Practice

  1. Import the random module and print a random number from 1 to 6.
  2. Create a module with a function that converts Celsius to Fahrenheit.
  3. Create a virtual environment and install requests.

Hands-on exercise

Create a module called money.py with a function format_naira(amount).
It should return a string like ₦1,250.00.
Then import it in main.py and print the result for 1250.

Recap

Modules split code into files, packages add outside code, and virtual environments keep each project's dependencies separate.

Example

import math
from datetime import date, timedelta

print(math.sqrt(81))          # 9.0
print(date.today())
print(date.today() + timedelta(days=7))

Exercises

Exercise 1. A reusable module Easy
Create a module called money.py with a function format_naira(amount).
It should return a string like ₦1,250.00.
Then import it in main.py and print the result for 1250.
Python exercise-1.py
Expected Output
₦1,250.00

Lesson Nav

Lesson sections