πŸ”„ Quick Recap (Day 15)

  • You mastered file I/O and exception handling with context managers and try/except.

🎯 What You’ll Learn Today

  1. What a virtual environment is and why it’s essential.

  2. How to create and activate a virtual environment using the built‑in venv module.

  3. How to install, list, update, and remove packages with pip.

  4. How to freeze your project’s dependencies to share or recreate the environment.

πŸ“– Why Virtual Environments?

Each Python project can have its own set of libraries and versions. A virtual environment isolates these dependencies so one project’s updates won’t break another’s:

  • Isolation: Keeps project libraries separate.

  • Reproducibility: Ensures consistency across machines or teammates.

  • Clean Global Python: Avoids cluttering the system-wide installation.

πŸ“– Creating & Activating with venv

  1. Create a project folder called learn-python-30.

  2. Open your terminal in the project folder.

  3. Run:

    python -m venv env
    • This creates an env directory containing Python and pip for this project.

  4. Activate the environment:

    • Windows (PowerShell): .\env\Scripts\Activate.ps1

    • Windows (CMD): env\Scripts\activate

    • macOS/Linux: source env/bin/activate

  5. Your prompt now shows (env), indicating the environment is active.

πŸ“– Managing Packages with pip

With the virtual env active, use pip to manage packages:

  • Install: pip install requests

  • List: pip list

  • Upgrade: pip install --upgrade requests

  • Uninstall: pip uninstall requests

Freezing & Sharing

Save exact versions to requirements.txt:

pip freeze > requirements.txt

Recreate the environment elsewhere with:

pip install -r requirements.txt

πŸ§™β€β™‚οΈ Take the Wand and Try Yourself

  1. Run python -m venv env to create an environment.

  2. Activate it according to your OS.

  3. Install two packages (e.g., requests, numpy).

  4. Run pip list to confirm installation.

  5. Freeze dependencies: pip freeze > requirements.txt.

  6. Deactivate with deactivate, then in a new folder, recreate:

    python -m venv env2
    source env2/bin/activate
    pip install -r requirements.txt
    pip list
  7. Confirm you see the same packages and versions.

Expected outcome:

  • Command prompt shows (env) when active.

  • pip list displays installed packages.

  • requirements.txt lists exact package versions.

  • Recreated environment matches original packages.

Up next: Day 17: Standard Library Deep Dive

Keep Reading