π Quick Recap (Day 15)
You mastered file I/O and exception handling with context managers and
try/except.
π― What Youβll Learn Today
What a virtual environment is and why itβs essential.
How to create and activate a virtual environment using the builtβin
venvmodule.How to install, list, update, and remove packages with pip.
How to freeze your projectβs dependencies to share or recreate the environment.
π Why Virtual Environments?
Each Python project can have its own set of libraries and versions. A virtual environment isolates these dependencies so one projectβs updates wonβt break anotherβs:
Isolation: Keeps project libraries separate.
Reproducibility: Ensures consistency across machines or teammates.
Clean Global Python: Avoids cluttering the system-wide installation.
π Creating & Activating with venv
Create a project folder called
learn-python-30.Open your terminal in the project folder.
Run:
python -m venv envThis creates an
envdirectory containing Python and pip for this project.
Activate the environment:
Windows (PowerShell):
.\env\Scripts\Activate.ps1Windows (CMD):
env\Scripts\activatemacOS/Linux:
source env/bin/activate
Your prompt now shows
(env), indicating the environment is active.
π Managing Packages with pip
With the virtual env active, use pip to manage packages:
Install:
pip install requestsList:
pip listUpgrade:
pip install --upgrade requestsUninstall:
pip uninstall requests
Freezing & Sharing
Save exact versions to requirements.txt:
pip freeze > requirements.txtRecreate the environment elsewhere with:
pip install -r requirements.txtπ§ββοΈ Take the Wand and Try Yourself
Run
python -m venv envto create an environment.Activate it according to your OS.
Install two packages (e.g.,
requests,numpy).Run
pip listto confirm installation.Freeze dependencies:
pip freeze > requirements.txt.Deactivate with
deactivate, then in a new folder, recreate:python -m venv env2 source env2/bin/activate pip install -r requirements.txt pip listConfirm you see the same packages and versions.
Expected outcome:
Command prompt shows
(env)when active.pip listdisplays installed packages.requirements.txtlists exact package versions.Recreated environment matches original packages.
Up next: Day 17: Standard Library Deep Dive