Installing Packages in Python
Beyond the Standard Library and your own modules, Python supports external packages — reusable code written by the community or third-party developers.
To manage external packages, Python uses:
pip — Python’s built-in package installer
PyPI — The Python Package Index, a large repository of open-source Python packages
What Is pip?
pipis the official package manager for Python.- It allows you to download, install, upgrade, and remove packages from PyPI.
- You can use
pipdirectly from the command line.
Installing a Package
Basic Syntax:
pip install package_nameExample 1: Install requests Package
pip install requestsExplanation:
- Installs the popular
requestslibrary for working with HTTP.
Example 2: Using Installed Package
requests_example.py
import requests
response = requests.get('https://api.github.com')
print("Status Code:", response.status_code)output.txt
Status Code: 200Checking Installed Packages
pip listExplanation:
- Lists all installed packages and their versions.
Upgrading a Package
pip install --upgrade package_nameExample:
pip install --upgrade requestsUninstalling a Package
pip uninstall package_nameExample:
pip uninstall requestsInstalling a Specific Version
pip install package_name==version_numberExample:
pip install Django==4.2.0Using a requirements.txt File
In larger projects, you often maintain a list of required packages:
File: requirements.txt
requests==2.31.0
Django>=4.2
pandasInstall all at once:
pip install -r requirements.txtVirtual Environments
For managing project-specific dependencies, it’s best to use a virtual environment:
python -m venv venv
source venv/bin/activate # On Linux/macOS
venv\Scripts\activate # On WindowsThen:
pip install package_nameSummary
- Use
pipto install external packages from PyPI. - Installed packages can be used via
import. - You can install, upgrade, or uninstall packages easily.
- Manage dependencies cleanly with virtual environments and
requirements.txt.
Next, we will explore Object-Oriented Programming (OOP) — a core part of writing organized, scalable Python code.