Python Virtual Environment Tutorial

A Python virtual environment allows you to create an isolated environment for each project. This prevents conflicts between package versions used by different projects. A Python virtual environment is an isolated workspace that allows you to manage project-specific dependencies without affecting the system-wide Python installation or other projects.This tutorial provides a step-by-step guide for Windows users on how to install Python, create and activate a virtual environment, install and manage packages using pip. By following this guide, you can maintain clean, organized, and reproducible Python development environments for all your projects.


Step 1: Install Python

  1. Download Python from:
    https://www.python.org/downloads/
  2. During installation, check:✅ Add Python to PATH
  3. Click Install Now.

Step 2: Verify Python Installation

Open Command Prompt (Win + Rcmd).

Check Python version:

python --version

or

py --version

Example:

Python 3.12.5

Step 3: Navigate to Your Project

Example:

cd D:\Projects\MyPythonProject

or

cd C:\Users\YourName\Documents\PythonProjects\Demo

Step 4: Create a Virtual Environment

Run:

python -m venv venv

or

py -m venv venv

This creates a folder named:

venv/

Project structure:

MyPythonProject/
│
├── venv/
├── main.py

Step 5: Activate the Virtual Environment

Command Prompt (CMD)

venv\Scripts\activate

You will see:

(venv) C:\Projects\MyPythonProject>

PowerShell

venv\Scripts\Activate.ps1

If you get an execution policy error:

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Then activate again:

venv\Scripts\Activate.ps1

Git Bash

source venv/Scripts/activate

Useful Commands

TaskCommand
Check Python versionpython --version
Check pip versionpip --version
Create virtual environmentpython -m venv venv
Activate (CMD)venv\Scripts\activate
Activate (PowerShell)venv\Scripts\Activate.ps1
Activate (Git Bash)source venv/Scripts/activate
Install packagepip install package_name
List installed packagespip list
Save dependenciespip freeze > requirements.txt
Install dependenciespip install -r requirements.txt
Deactivate environmentdeactivate
Delete environmentrmdir /s /q venv

Example Workflow

mkdir MyProject
cd MyProject

python -m venv venv

venv\Scripts\activate

Best Practices

  • Create a separate virtual environment for each Python project.
  • Do not commit the venv folder to Git. Add it to your .gitignore file:venv/
  • Always activate the virtual environment before running your project or installing packages.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.