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
- Open the terminal in your project folder.
- Create:
python -m venv .venv. - Activate on Windows:
.venv\\Scripts\\activate. On Mac:source .venv/bin/activate. - You see
(.venv)at the start of the prompt. - Install packages with pip — they go into this venv only.
- Run
deactivatewhen you are done.
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.
Ravindra Bagale's Tip – मराठी
VS Code मध्ये .venv बनवल्यावर "Python: Select Interpreter" ने तो निवडा. मग Run button आणि notebooks तोच वापरतात.
Ravindra Bagale's Tip – हिंदी
VS Code में .venv बनाने के बाद "Python: Select Interpreter" से उसे चुनो. फिर Run button और notebooks वही इस्तेमाल करते हैं.