12 Python Virtual Environment

1. What is a Virtual Environment?

A virtual environment is a separate space for Python projects.

In simple words:
👉 Each project gets its own Python packages
👉 Packages of one project do not affect other projects
👉 It keeps your system clean and safe

2. Why Do We Need Virtual Environment?

Without virtual environment:

  • Package versions can conflict

  • One project can break another

With virtual environment:

  • Each project has its own setup

  • Easy to manage packages

  • Professional way of working

3. Create a Virtual Environment

Python provides a built-in tool called venv.

Create Virtual Environment

python -m venv myenv

👉 myenv is the environment name.

4. Activate Virtual Environment

Windows


 

macOS / Linux


 

After Activation

You will see:


 

at the beginning of terminal.

5. Install Packages Inside Virtual Environment

Example


 

👉 Package is installed only inside this environment.

6. Check Installed Packages

Example


 

7. Use Installed Package in Python

Example


 

8. Deactivate Virtual Environment

Example


 

9. Create requirements.txt

This file saves package list.

Create File


 

Install from File


 

10. Virtual Environment Folder Structure

After creation:


 

👉 Do NOT edit these files.

11. Common Beginner Mistakes

❌ Forgetting to Activate Environment


 

👉 Package installs globally.

❌ Deleting Environment Accidentally

👉 You can recreate it anytime using venv.

12. Simple Practice Example

Example: New Project Setup


 

13. Virtual Environment vs Global Python

Virtual Env Global Python
Safe Risky
Project-based System-wide
Recommended Not recommended

14. Summary (Python Virtual Environment)

✔ Keeps projects separate
✔ Avoids package conflict
✔ Uses venv module
✔ Easy to create & delete
✔ Must-have for Python developers

📘 Perfect for Beginner eBook

This chapter is ideal for:

  • Python beginner books

  • School & college students

  • Self-learners

If you want next, I can write:

  • File Handling

  • Exception Handling

  • Command Line Arguments

  • Mini Python Projects

Just tell me 😊

You may also like...