Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING BASH RUST

Python Tutorial

Python HOME Python Intro Python Get Started Python Syntax Python Comments Python Variables Python Data Types Python Numbers Python Casting Python Strings Python Booleans Python Operators Python Lists Python Tuples Python Sets Python Dictionaries Python If...Else Python Match Python While Loops Python For Loops Python Functions Python Lambda Python Arrays Python Classes/Objects Python Inheritance Python Iterators Python Polymorphism Python Scope Python Modules Python Dates Python Math Python JSON Python RegEx Python PIP Python Try...Except Python User Input Python String Formatting Python VirtualEnv

File Handling

Python File Handling Python Read Files Python Write/Create Files Python Delete Files

Python Modules

NumPy Tutorial Pandas Tutorial SciPy Tutorial Django Tutorial

Python Matplotlib

Matplotlib Intro Matplotlib Get Started Matplotlib Pyplot Matplotlib Plotting Matplotlib Markers Matplotlib Line Matplotlib Labels Matplotlib Grid Matplotlib Subplot Matplotlib Scatter Matplotlib Bars Matplotlib Histograms Matplotlib Pie Charts

Machine Learning

Getting Started Mean Median Mode Standard Deviation Percentile Data Distribution Normal Data Distribution Scatter Plot Linear Regression Polynomial Regression Multiple Regression Scale Train/Test Decision Tree Confusion Matrix Hierarchical Clustering Logistic Regression Grid Search Categorical Data K-means Bootstrap Aggregation Cross Validation AUC - ROC Curve K-nearest neighbors

Python MySQL

MySQL Get Started MySQL Create Database MySQL Create Table MySQL Insert MySQL Select MySQL Where MySQL Order By MySQL Delete MySQL Drop Table MySQL Update MySQL Limit MySQL Join

Python MongoDB

MongoDB Get Started MongoDB Create DB MongoDB Collection MongoDB Insert MongoDB Find MongoDB Query MongoDB Sort MongoDB Delete MongoDB Drop Collection MongoDB Update MongoDB Limit

Python Reference

Python Overview Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods Python File Methods Python Keywords Python Exceptions Python Glossary

Module Reference

Random Module Requests Module Statistics Module Math Module cMath Module

Python How To

Remove List Duplicates Reverse a String Add Two Numbers

Python Examples

Python Examples Python Compiler Python Exercises Python Quiz Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training

Python Virtual Environment


What is a Virtual Environment?

A virtual environment in Python is an isolated environment on your computer, where you can run and test your Python projects.

It allows you to manage project-specific dependencies without interfering with other projects or the original Python installation.

Think of a virtual environment as a separate container for each Python project. Each container:

  • Has its own Python interpreter
  • Has its own set of installed packages
  • Is isolated from other virtual environments
  • Can have different versions of the same package

Using virtual environments is important because:

  • It prevents package version conflicts between projects
  • Makes projects more portable and reproducible
  • Keeps your system Python installation clean
  • Allows testing with different Python versions

Creating a Virtual Environment

Python has the built-in venv module for creating virtual environments.

To create a virtual environment on your computer, open the command prompt, and navigate to the folder where you want to create your project, then type this command:

Example

Run this command to create a virtual environment named myfirstproject:

C:\Users\Your Name> python -m venv myfirstproject
$ python -m venv myfirstproject

This will set up a virtual environment, and create a folder named "myfirstproject" with subfolders and files, like this:

Result

The file/folder structure will look like this:

myfirstproject
  Include
  Lib
  Scripts
  .gitignore
  pyvenv.cfg

Activate Virtual Environment

To use the virtual environment, you have to activate it with this command:

Example

Activate the virtual environment:

C:\Users\Your Name> myfirstproject\Scripts\activate
$ source myfirstproject/bin/activate

After activation, your prompt will change to show that you are now working in the active environment:

Result

The command line will look like this when the virtual environment is active:

(myfirstproject) C:\Users\Your Name>
(myfirstproject) ... $

Install Packages

Once your virtual environment is activated, you can install packages in it, using pip:

Example

Install Matplotlib in the virtual environment:

(myfirstproject) C:\Users\Your Name> pip install matplotlib
(myfirstproject) ... $ pip install matplotlib

Result

MatplotLib is installed only in the virtual environment:

Collecting matplotlib
  Using cached matplotlib-3.10.1-cp313-cp313-win_amd64.whl.metadata (11 kB)
Collecting contourpy>=1.0.1 (from matplotlib)
  Downloading contourpy-1.3.2-cp313-cp313-win_amd64.whl.metadata (5.5 kB)
Collecting cycler>=0.10 (from matplotlib)
  Using cached cycler-0.12.1-py3-none-any.whl.metadata (3.8 kB)
Collecting fonttools>=4.22.0 (from matplotlib)
  Downloading fonttools-4.57.0-cp313-cp313-win_amd64.whl.metadata (104 kB)
Collecting kiwisolver>=1.3.1 (from matplotlib)
  Using cached kiwisolver-1.4.8-cp313-cp313-win_amd64.whl.metadata (6.3 kB)
Requirement already satisfied: numpy>=1.23 in c:\users\stale\myfirstproject\lib\site-packages (from matplotlib) (2.2.5)
Collecting packaging>=20.0 (from matplotlib)
  Downloading packaging-25.0-py3-none-any.whl.metadata (3.3 kB)
Collecting pillow>=8 (from matplotlib)
  Downloading pillow-11.2.1-cp313-cp313-win_amd64.whl.metadata (9.1 kB)
Collecting pyparsing>=2.3.1 (from matplotlib)
  Using cached pyparsing-3.2.3-py3-none-any.whl.metadata (5.0 kB)
Collecting python-dateutil>=2.7 (from matplotlib)
  Using cached python_dateutil-2.9.0.post0-py2.py3-none-any.whl.metadata (8.4 kB)
Collecting six>=1.5 (from python-dateutil>=2.7->matplotlib)
  Using cached six-1.17.0-py2.py3-none-any.whl.metadata (1.7 kB)
Using cached matplotlib-3.10.1-cp313-cp313-win_amd64.whl (8.1 MB)
Downloading contourpy-1.3.2-cp313-cp313-win_amd64.whl (223 kB)
Using cached cycler-0.12.1-py3-none-any.whl (8.3 kB)
Downloading fonttools-4.57.0-cp313-cp313-win_amd64.whl (2.2 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.2/2.2 MB 46.0 MB/s eta 0:00:00
Using cached kiwisolver-1.4.8-cp313-cp313-win_amd64.whl (71 kB)
Downloading packaging-25.0-py3-none-any.whl (66 kB)
Downloading pillow-11.2.1-cp313-cp313-win_amd64.whl (2.7 MB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.7/2.7 MB 92.3 MB/s eta 0:00:00
Using cached pyparsing-3.2.3-py3-none-any.whl (111 kB)
Using cached python_dateutil-2.9.0.post0-py2.py3-none-any.whl (229 kB)
Using cached six-1.17.0-py2.py3-none-any.whl (11 kB)
Installing collected packages: six, pyparsing, pillow, packaging, kiwisolver, fonttools, cycler, contourpy, python-dateutil, matplotlib
Successfully installed contourpy-1.3.2 cycler-0.12.1 fonttools-4.57.0 kiwisolver-1.4.8 matplotlib-3.10.1 packaging-25.0 pillow-11.2.1 pyparsing-3.2.3 python-dateutil-2.9.0.post0 six-1.17.0

[notice] A new release of pip is available: 25.0.1 -> 25.1.1
[notice] To update, run: python.exe -m pip install --upgrade pip

Using Package

Now that the Matplotlib module is installed in your virtual environment, lets use it to display a diagram.

Create a file called test.py on your computer. You can place it wherever you want, but I will place it in the same location as the myfirstproject folder -not in the folder, but in the same location.

Open the file and insert these three lines in it:

Example

Insert three lines in test.py:

import matplotlib.pyplot as plt

plt.plot([0, 6], [0, 250])
plt.show()

Then, try to execute the file while you are in the virtual environment:

Example

Execute test.py in the virtual environment:

(myfirstproject) C:\Users\Your Name> python test.py
(myfirstproject) ... $ python test.py

As a result, you will get a diagram showing a line plot from position 0, 0 to 6, 250:

Result


Deactivate Virtual Environment

To deactivate the virtual environment use this command:

Example

Deactivate the virtual environment:

(myfirstproject) C:\Users\Your Name> deactivate
(myfirstproject) ... $ deactivate

As a result, you are now back in the normal command line interface:

Result

Normal command line interface:

C:\Users\Your Name>
$

If you try to execute the test.py file outside of the virtual environment, you will get an error because Matplotlib is missing. It was only installed in the virtual environment:

Example

Execute test.py outside of the virtual environment:

C:\Users\Your Name> python test.py
$ python test.py

Result

Error because Matploblib is missing:

Traceback (most recent call last):
  File "C:\Users\Your Name\test.py", line 1, in <module>
    import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'

Note: The virtual environment myfirstproject still exists, it is just not activated. If you activate the virtual environment again, you can execute the test.py file, and the diagram will be displayed.


Delete Virtual Environment

Another nice thing about working with a virtual environment is that when you, for some reason want to delete it, there are no other projects depend on it, and only the modules and files in the specified virtual environment are deleted.

To delete a virtual environment, you can simply delete its folder with all its content. Either directly in the file system, or use the command line interface like this:

Example

Delete myfirstproject from the command line interface:

C:\Users\Your Name> rmdir /s /q myfirstproject
$ rm -rf myfirstproject


×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2025 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.