Modules, Packages and Virtual Environments
💻 PythonSplit code into modules, install packages and keep each project isolated.
Real programs are built from many files and third-party libraries. Modules keep that organized and virtual environments keep it clean.
- 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.txtUsing a Package
Once installed, import the package like any module. Keep a requirements.txt so another machine can install the same versions.
Practice
- Import the random module and print a random number from 1 to 6.
- Create a module with a function that converts Celsius to Fahrenheit.
- 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
It should return a string like ₦1,250.00.
Then import it in main.py and print the result for 1250.
Expected Output
₦1,250.00
Lesson Nav
Python Course
0/9 lessons completed
- 1 Python Basics Tutorial
- 2 Conditionals and Loops Tutorial
- 3 Functions and Lists Tutorial
- 4 Strings and Lists Tutorial
- 5 Build a Student Manager Project
- 6 Dictionaries Tutorial
- 7 Reading and Writing Files Tutorial
- 8 Error Handling with Exceptions Tutorial
- 9 Modules, Packages and Virtual Environments Tutorial