How to Install Python Packages Using pip

Learn how to install and manage third-party packages in Python using pip. Discover virtual environments, requirements.txt, and basic commands.

Try Code in Editor

Explanation

A key reason for Python's massive popularity is its rich ecosystem of third-party packages, hosted on the Python Package Index (PyPI). These packages allow you to easily integrate web scraping, machine learning, web servers, and data analysis into your code. To install these packages, Python provides the official package manager tool, `pip`.

To install a package, you run `pip install package_name` in your system's terminal. This fetches the latest version of the package from PyPI and installs it on your system. You can specify precise versions using syntax like `pip install package_name==1.2.3` or update existing packages with the `--upgrade` flag.

In modern development, it is critical to use virtual environments (like `venv`) to isolate package dependencies per project, preventing conflicts between global system libraries. Dependencies can then be exported to a `requirements.txt` file and installed in bulk using the `pip install -r requirements.txt` command.

Step-by-Step Implementation

  1. 1

    Open your terminal or command prompt (do not write pip commands inside a Python file).

  2. 2

    Run pip install <package_name> to download the library from PyPI.

  3. 3

    Run pip freeze > requirements.txt to save all current project dependencies.

Code Example

This simulation shows how common pip commands are written and configured in terminal environments.

pip_guide.py
Try in Editor
# Note: pip is a command-line tool, not a Python code keyword.
# Below is a simulation showing how pip commands are written and run:

command_install = "pip install requests"
command_upgrade = "pip install --upgrade requests"
command_requirements = "pip install -r requirements.txt"

print("To install a package, run:")
print(f"  $ {command_install}")
print("To upgrade an existing package, run:")
print(f"  $ {command_upgrade}")
print("To install from a requirements file, run:")
print(f"  $ {command_requirements}")
Terminal Output
To install a package, run:
  $ pip install requests
To upgrade an existing package, run:
  $ pip install --upgrade requests
To install from a requirements file, run:
  $ pip install -r requirements.txt

Frequently Asked Questions

How do I fix the 'pip command not found' error?

Ensure Python is added to your system's PATH variable, or try calling the module wrapper: python -m pip install <package>.

What is the purpose of a virtual environment (venv)?

It isolates project dependencies in a local folder, preventing libraries in one project from breaking or conflicting with libraries in another.

Related How-To Guides

Recommended Python Resources

Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.