Working with Popular Libraries
What Is a Package?
A package in Python is a collection of modules organized in a directory hierarchy. Packages allow you to structure your code into reusable, shareable components. The Python Package Index (PyPI) hosts thousands of third-party packages.
- Packages are installed using
pip(Python’s package installer). - Each package contains one or more modules.
- Popular packages simplify tasks like data analysis, web development, and machine learning.
Installing Packages with pip
Use the command line to install packages:
# Install a package
pip install requests
# Install a specific version
pip install numpy==1.24.0
# Upgrade a package
pip install --upgrade pandas
# List installed packages
pip listPopular Built-in & Third-Party Packages
| Package | Type | Common Use Case |
|---|---|---|
math, os, sys |
Built-in | Math operations, OS interaction, system control |
requests |
Third-party | HTTP requests (APIs, web scraping) |
numpy |
Third-party | Numerical computing, arrays, math |
pandas |
Third-party | Data manipulation and analysis |
matplotlib |
Third-party | Data visualization (charts, plots) |
json |
Built-in | Working with JSON data |
Example: Using the requests Package
Fetch data from a public API (e.g., JSONPlaceholder):
1. Install and Use
requests# In terminal:
# pip install requests
# In your Python script:
import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
data = response.json()
print(data["title"]) # Output: "sunt aut facere..."Example: Using numpy for Arrays
2. Numerical Operations with
numpy# pip install numpy
import numpy as np
arr = np.array([1, 2, 3, 4])
squared = arr ** 2
print(squared) # [1 4 9 16]
mean_val = np.mean(arr)
print(mean_val) # 2.5Example: Data Analysis with pandas
3. Working with DataFrames
# pip install pandas
import pandas as pd
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35]
}
df = pd.DataFrame(data)
print(df)
# Name Age
# 0 Alice 25
# 1 Bob 30
# 2 Charlie 35
print(df["Age"].mean()) # 30.0Example: Plotting with matplotlib
4. Creating a Simple Line Chart
# pip install matplotlib
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y, marker='o')
plt.title("y = x²")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()Virtual Environments (Best Practice)
To avoid dependency conflicts, use virtual environments:
# Create a virtual environment
python -m venv myenv
# Activate it (Windows)
myenv\Scripts\activate
# Activate it (macOS/Linux)
source myenv/bin/activate
# Now install packages safely
pip install requests pandasWhen done, deactivate with:
deactivateImporting from Packages
Once installed, import just like standard modules:
import requestsfrom numpy import array, meanimport pandas as pd(common alias)
Common Pitfalls & Tips
- ❌ **Don’t install packages globally**—use virtual environments.
- ❌ **Avoid outdated tutorials**—package APIs evolve.
- ✅ **Read official documentation** (e.g., requests docs).
- ✅ **Use
requirements.txt** to share dependencies:
# requirements.txt
requests==2.31.0
numpy==1.24.3
pandas==2.0.3Install all at once with:
pip install -r requirements.txtKey Takeaways
- Packages extend Python’s capabilities beyond the standard library.
- Use
pipto install, upgrade, and manage packages. - Popular packages like
requests,numpy, andpandassolve real-world problems efficiently. - Always use virtual environments for project isolation.
- Document dependencies with
requirements.txt.