Skip to Content

How to create a virtual environment in Python

In the world of Python development, managing dependencies and packages properly is very important. If you install everything globally, it can easily lead to version conflicts and unnecessary issues. That's where virtual environments come into the picture.

A virtual environment helps you create an isolated space for your Python projects. Each project can have its own dependencies, regardless of what dependencies every other project has.

In this blog post, we will explain how to create a virtual environment in Python step-by-step, suitable for both beginners and working professionals.

What is a Virtual Environment?

A virtual environment is a self-contained directory that contains a Python installation for a particular version of Python, plus a number of additional packages. You can create as many virtual environments as you want and keep them separate for each project.

Prerequisites

Before we start, make sure Python is installed on your system. You can check this by running the following command in your terminal or command prompt:

python --version

or

python3 --version

If Python is not installed, you can download it from the official website: https://www.python.org/downloads/

Step 1: Install virtualenv (if not already installed)

While Python 3.3+ comes with the venv module, many developers also use virtualenv for better control.

To install virtualenv​, run:

pip install virtualenv


Step 2: Create the Virtual Environment

You can create a virtual environment using either venv or virtualenv.

Using venv​ (recommended if using Python 3.3+):

python3 -m venv env_name


Example:

python3 -m venv myprojectenv


Using virtualenv​:

virtualenv env_name


Example:

virtualenv myprojectenv


Step 3: Activate the Virtual Environment

Once created, you need to activate it.

On Windows: .\myprojectenv\Scripts\activate

On Linux/macOS: source myprojectenv/bin/activate


After activation, you’ll see the environment name in your terminal prompt.

(myprojectenv) $

This indicates that you are now working inside the virtual environment.


Step 4: Install Packages Inside the Virtual Environment

Now you can install any Python packages you want, and they will only be available inside this environment.


pip install requests

Step 5: Deactivate the Virtual Environment

When you are done working, simply deactivate the virtual environment using:

deactivate

This will return you to the global Python environment.

 


Creating a virtual environment is a best practice that every Python developer in India and around the world should follow. It makes your code more manageable, avoids conflicts, and helps maintain clean project setups.

Whether you are working on a personal project, college assignment, or professional application, setting up a virtual environment should be your first step.

Happy Coding! 🇮🇳🐍


Hope you find it helpful!!

How to convert Python script to exe