Back to Blog
Virtual Environments and Package Management with Pip

Virtual Environments and Package Management with Pip

November 26, 2026
Reynov Christian

Up until now, every program in this series has used only the Python Standard Library. That took us surprisingly far, from file storage to CSV reports and JSON configs. Soon, however, you will want to connect to web APIs, scrape web pages, or build web apps. For those tasks, Python developers rely on third-party packages built by the global Python community.

In this lesson, you will learn what pip is, why installing packages globally causes headaches, how to create isolated virtual environments with venv, and how to set up a clean workspace with the popular requests library.

1. What Are Third-Party Packages and Pip?

A third-party package is code written and shared by other developers on PyPI (the Python Package Index at pypi.org). Examples include requests for making web requests, flask for building websites, and pandas for data analysis.

pip is Python’s built-in package installer. It downloads packages from PyPI and installs them for you. One beginner trap to watch out for: pip commands run in your operating system terminal (PowerShell, Command Prompt, or bash/zsh), not inside the Python >>> REPL.

2. Why Global Installations Cause Conflicts

Imagine you build Project A today using version 1.0 of a library. Six months later, you start Project B, which requires version 2.0 of the same library. If you install packages globally (into one shared folder for your whole computer), upgrading to version 2.0 can break Project A.

The solution is a virtual environment: a self-contained folder (usually named .venv) inside each project that holds its own private copy of Python and its own installed packages.

3. Creating and Activating a Virtual Environment

Create a new folder for your project, open your terminal inside that folder, and create a virtual environment with Python’s built-in venv module:

mkdir weather_workspace
cd weather_workspace
python -m venv .venv

Next, activate the environment so your terminal uses the private Python inside .venv. The activation command depends on your operating system:

# Windows (PowerShell)
.venv\Scripts\Activate.ps1

# Windows (Command Prompt / cmd)
.venv\Scripts\activate.bat

# macOS and Linux
source .venv/bin/activate

When activation succeeds, you will see (.venv) at the beginning of your terminal prompt. If Windows PowerShell blocks the script with an execution policy error, run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once and try activating again. To leave the environment later, simply type deactivate.

4. Installing Packages and Managing requirements.txt

With (.venv) active, install packages using python -m pip install. Using python -m pip guarantees you are installing into the active virtual environment’s Python.

# Install the requests library
python -m pip install requests

# See what is installed in this environment
python -m pip list

# Save the exact package versions to requirements.txt
python -m pip freeze > requirements.txt

The requirements.txt file acts like a recipe list for your project. If you share your code on GitHub or move to a new laptop, anyone can recreate the exact same environment in one command: python -m pip install -r requirements.txt. Never commit the .venv folder itself to Git; commit requirements.txt instead.

5. Practical Project: Clean Workspace and URL Status Checker

Now let’s verify that your virtual environment and requests installation work properly. Inside your weather_workspace folder (with (.venv) active), create a file named check_website.py. This small script checks whether a website responds and prints its HTTP status code safely.

At the bottom of the script, if __name__ == "__main__": is a standard Python guard that runs main() only when you execute this file directly (covered in detail in Lesson 15).

import requests


def check_url(url: str) -> None:
    """Send a GET request and print the HTTP status code."""
    try:
        response = requests.get(url, timeout=10)
        print(f"URL:    {url}")
        print(f"Status: {response.status_code} ({response.reason})")
    except requests.RequestException as error:
        print(f"Could not reach {url}: {error}")


def main() -> None:
    """Prompt the user for a URL and test the connection."""
    print("=== Website Status Checker ===")
    raw_url = input("Enter a website URL (e.g., https://python.org): ").strip()

    if not raw_url:
        print("URL cannot be empty.")
        return

    if not raw_url.startswith(("http://", "https://")):
        raw_url = f"https://{raw_url}"

    check_url(raw_url)


if __name__ == "__main__":
    main()

Run python check_website.py while (.venv) is active and enter https://python.org. You should see Status: 200 (OK). If you run the same script after typing deactivate, Python will raise ModuleNotFoundError: No module named 'requests', proving that your package is cleanly isolated inside .venv.

Common Beginner Mistakes

  • Typing pip install inside the >>> Python REPL: pip is a terminal command, not Python syntax. Exit the REPL with exit() before running pip.
  • Forgetting to activate .venv before installing: If you do not see (.venv) in your terminal prompt, pip will install packages into your global Python instead of your project.
  • Selecting the wrong interpreter in VS Code: Even when .venv exists, VS Code may still point to global Python. Press Ctrl+Shift+P (or Cmd+Shift+P on macOS), choose Python: Select Interpreter, and pick the one inside .venv.
  • Uploading .venv to GitHub or cloud drives: Virtual environments contain thousands of machine-specific files. Always add .venv/ to your .gitignore file and share only requirements.txt.

Try It Yourself

  • Multi-Site Checker (multi_check.py): Store 3 to 5 website URLs in a list and loop through them with check_url() to see which sites respond with status 200.
  • Rebuild from Scratch (rebuild_env_notes.txt): Delete your .venv folder, create a brand-new .venv, activate it, and run python -m pip install -r requirements.txt to verify your project still runs cleanly.
  • Response Timer (check_speed.py): Update check_url() to print response.elapsed.total_seconds() formatted to 2 decimal places so you can see how fast each site responds.

Frequently Asked Questions

Should I name my virtual environment venv or .venv?

Both work, but .venv (with a leading dot) is the modern convention. Most editors like VS Code detect .venv automatically and keep it neatly tucked away in your file explorer.

Do I need to create a new virtual environment for every project?

Yes, for any project that installs third-party packages. Virtual environments are lightweight and easy to recreate, and keeping one per project prevents version conflicts.

What is the difference between pip install and python -m pip install?

If you have multiple Python versions installed, plain pip might point to the wrong one. Running python -m pip install guarantees that packages are installed for the exact Python interpreter you are currently using.

Why did VS Code show a yellow squiggle under import requests?

That happens when VS Code is still using your global Python interpreter instead of .venv. Use Python: Select Interpreter to switch to .venv and the warning will disappear.

Want to review Python’s built-in modules before adding external libraries? Check out the previous lesson: Python Modules and Standard Library Highlights. In our next article, Creating Custom Modules and Multi-File Projects, you will learn how to split growing scripts cleanly across multiple Python files.

Learning programming works best as a collaborative process, and your questions and insights help make these tutorials more effective for everyone. If you run into a PowerShell activation issue, get a ModuleNotFoundError, or have questions about setting up requirements.txt, please share your experience in the comments. Your feedback helps create a learning community where we can all benefit from each other’s discoveries and solutions.

You Might Also Like

Comments

Loading comments…

Leave a Comment

0/5000