Mathew K Analytics

Lesson 3 · Python for Data Science

Mastering Virtual Environments in Python for Effective Data Science Projects

Welcome! In this lesson, we will learn what virtual environments are and why they matter. You will see how virtual environments help keep your Python…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb
 

Virtual Environments in Python: A Beginner's Guide#

Welcome! In this lesson, we will learn what virtual environments are and why they matter.

You will see how virtual environments help keep your Python projects organized and safe.

Let us get started!

What is a Virtual Environment?#

A virtual environment is like a fresh space for every Python project.

It keeps the packages and settings for one project separate from all others.

This helps avoid conflicts between different projects.

# Let us check our Python version before anything else.
import sys
print("Your current Python version is:", sys.version)
 
 
Your current Python version is: 3.12.1 (tags/v3.12.1:2305ca5, Dec  7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)]

Why Use Virtual Environments?#

Suppose you have two projects. One uses Flask version 1.1 and another uses Flask version 2.0.

If both projects share the same settings, it can cause problems.

A virtual environment makes sure each project works with the version it needs.

# You do not need to install venv if you are using Python 3.3 or later.
# The venv module is built into modern Python versions.
import venv
print("venv module is ready to help us create virtual environments.")
venv module is ready to help us create virtual environments.
# Let us create a name for our first virtual environment.
venv_name = "my_first_env"
print("We will call our virtual environment:", venv_name)
We will call our virtual environment: my_first_env
# We cannot run system commands here, but this shows how to create a virtual environment.
print("To make a virtual environment, run:")
print("python -m venv my_first_env")
 
 
To make a virtual environment, run:
python -m venv my_first_env

How to Activate a Virtual Environment#

After you create the environment, you need to activate it.

On Windows, the command is:

my_first_env\Scripts\activate

On Mac or Linux, it is:

source my_first_env/bin/activate

# Let us pretend we activated our environment.
print("(my_first_env) Now you are in your virtual environment!")
(my_first_env) Now you are in your virtual environment!
# Each virtual environment has its own installed packages.
print("Try installing a package with:")
print("pip install requests")
Try installing a package with:
pip install requests
# Let us check which packages are installed inside the environment.
print("List the packages in your virtual environment with:")
print("pip list")
List the packages in your virtual environment with:
pip list
# You can use input() to ask for a new environment name.
name = input("Type a name for your new project environment: ")
print("Your chosen name is:", name)
Your chosen name is: my_test_env
 
# To leave the virtual environment, just deactivate it.
print("Deactivate with this command:")
print("deactivate")
Deactivate with this command:
deactivate
# Virtual environments are just folders.
import os
print("Is the folder for your venv present?", os.path.isdir(venv_name))
Is the folder for your venv present? False
# Clean up by deleting the virtual environment folder if you want.
import shutil
shutil.rmtree(venv_name, ignore_errors=True)
print("Virtual environment has been deleted (if it existed).")
Virtual environment has been deleted (if it existed).

Using requirements.txt Files#

A requirements.txt file lists all the packages your project needs.

You can install every package in the list with a single pip command.

This makes sharing your setup with others easy.

# Example: Save installed packages to a requirements.txt file.
print("To save your package list, run:")
print("pip freeze > requirements.txt")
To save your package list, run:
pip freeze > requirements.txt
# To install from requirements.txt, use this pip command:
print("pip install -r requirements.txt")
pip install -r requirements.txt
# Mini-project: Set up and use a virtual environment for a weather app.
print("Step 1: Create and activate a virtual environment named 'weather_env'.")
print("Step 2: Install requests with 'pip install requests'.")
print("Step 3: Write a small script that prints the current weather in your city.")
Step 1: Create and activate a virtual environment named 'weather_env'.
Step 2: Install requests with 'pip install requests'.
Step 3: Write a small script that prints the current weather in your city.
# Mini-project continued: Example code for weather app (using input).
city = input("Enter your city for a weather report: ")
print("Pretending to fetch weather for", city, "...")
# Imagine this is where requests would pull from a real weather API.
Pretending to fetch weather for Springfield ...
 
# Best practice: Always use a virtual environment for every project.
print("Virtual environments protect your projects from accidental changes.")
Virtual environments protect your projects from accidental changes.
# Troubleshooting: Command not found for venv?
print("If you see 'command not found', make sure you are using Python 3.3 or later and try 'python3 -m venv myenv'.")
If you see 'command not found', make sure you are using Python 3.3 or later and try 'python3 -m venv myenv'.
# Extra tip: You can name venv folders anything you like.
print("Choose names that help you remember the project.")
print("Examples: blog_env, homework_env, game_env")
Choose names that help you remember the project.
Examples: blog_env, homework_env, game_env
# Challenge: Can you create a new venv, install numpy, and check pip list inside?
print("Try this task: Set up a venv, install numpy, and use pip list to see it.")
Try this task: Set up a venv, install numpy, and use pip list to see it.

Recap: What Have We Learned?#

  • Virtual environments keep Python projects isolated.
  • Each project can have its own packages.
  • Using venv is healthy for your code.
  • requirements.txt lets you save and share setups.
  • Keeping things organized saves time and headaches.

Thanks for sticking with this beginner's guide to virtual environments in Python!

If you enjoyed the lesson, please hit the like button and share your thoughts in a comment.

Subscribe for more easy Python lessons and share this video with a friend who is learning too!

Happy coding!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.