Ravindra BagaleCourses & study guides मराठी Track your progress

Python Modules, pip and Virtual Environments (venv) Explained for Beginners

P10.4 How to Create a Python Virtual Environment (venv)

Why. Project A needs pandas 1.5, project B needs pandas 2.2. If both share one Python, one breaks. A virtual environment gives each project its own private set of packages.

What. A venv is a folder with its own Python and its own packages. You "activate" it before working.

How.

Create and use a venv

  1. Open the terminal in your project folder.
  2. Create: python -m venv .venv.
  3. Activate on Windows: .venv\\Scripts\\activate. On Mac: source .venv/bin/activate.
  4. You see (.venv) at the start of the prompt.
  5. Install packages with pip — they go into this venv only.
  6. Run deactivate when you are done.
1. Make a project folder2. python -m venv .venv3. Activate .venv4. pip install pandas ...5. Work on the project6. deactivate
Project setup with a virtual environment (read from top to bottom)

Worked example A — Create and activate (Windows).

Step 1 — What we do. We set up a venv for a retail analysis project.

Step 2 — Type and run this code.

cd retail-analysis
python -m venv .venv
.venv\Scripts\activate

Step 3 — Output you should see.

(.venv) C:\Users\you\retail-analysis>

Step 4 — What it means. The (.venv) prefix shows the venv is active. Packages now install into .venv.

Worked example B — Create and activate (Mac).

Step 1 — What we do. Same steps on a Mac.

Step 2 — Type and run this code.

cd retail-analysis
python3 -m venv .venv
source .venv/bin/activate

Step 3 — Output you should see.

(.venv) you@mac retail-analysis %

Step 4 — What it means. After activation, python and pip point to the venv, even on Mac.

Worked example C — Check you are inside the venv.

Step 1 — What we do. Python can tell us if it runs inside a virtual environment.

Step 2 — Type and run this code.

import sys
print(sys.prefix != sys.base_prefix)

Step 3 — Output you should see.

False

Step 4 — What it means. True means a venv is active; False means the main Python. (Here it shows the state of the computer that ran the example.)

Ravindra Bagale's Tip

In VS Code, after creating .venv, choose it with "Python: Select Interpreter". Then the Run button and notebooks use it.