← Back to Python Course | Chapter 8: Modules & Packages | Lesson 4 of 6

Python pip & Packages

What is pip?

pip is Python's package installer, letting you pull third-party code from the Python Package Index (PyPI) with a single command like 'pip install requests' instead of manually downloading and configuring a library yourself.

Example: What is pip?

python
# pip install requests
print("pip installs packages from PyPI")

The requirements.txt File

A requirements.txt file pins the exact packages (and often exact versions) a project depends on, so anyone else can recreate your environment with 'pip install -r requirements.txt' instead of guessing which libraries and versions you used.

Example: The requirements.txt File

python
# requirements.txt would contain:
# requests==2.31.0
# Install with: pip install -r requirements.txt
print("requirements.txt pins project dependencies")

Virtual Environments

A virtual environment creates an isolated Python installation just for one project, so installing a package there doesn't affect (or conflict with) packages installed for other projects on the same machine -- this is what makes reproducible, per-project dependencies possible.

Example: Virtual Environments

python
# python -m venv venv
# source venv/bin/activate
print("Virtual environments isolate per-project dependencies")

Querying Installed Packages

You can inspect where pip actually installs packages by checking a project's site-packages directory, which is useful for debugging 'why isn't Python finding my installed library' issues -- often the answer is that pip installed into a different Python environment than the one running your script.

Example: Querying Installed Packages

python
import sys
print(sys.prefix)  # shows which Python environment is active

Best Practices

Wrapping a third-party import in try/except ImportError lets your program fail with a clear, actionable message ('please install requests') instead of a confusing traceback, which matters most for optional dependencies that not every user of your script will need.

Example: Best Practices

python
try:
    import requests
except ImportError:
    print("please install requests")
🔒

Chapter Quiz — Complete all 6 topics to unlock

0/6 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.