Learning goals
Choose standard library tools or third party packages for a task and recognize their installation and runtime requirements.
Explanation
The standard library includes os for operating system interfaces, sys for interpreter information, pathlib for paths, json for serialization, and datetime for dates and times. Third party packages include Requests for HTTP, NumPy for arrays and numerical operations, pandas for tabular analysis, and Matplotlib for plots.
Start with the standard library when it meets the need. Add a dependency when its capabilities justify the installation and maintenance cost. Use the environment from Lesson 10.
Example 1 A standard library report
import os
import sys
import json
from pathlib import Path
from datetime import date, timedelta
report = {
"folder": Path.cwd().name,
"python_major": sys.version_info.major,
"os_family": os.name,
"due_date": str(date(2026, 9, 23) + timedelta(days=7)),
}
print(json.dumps(report, indent=2))Expected result: formatted JSON. due_date is "2026-09-30" and python_major is 3; folder and os_family depend on the machine. os.name commonly reports "nt" on Windows and "posix" on Unix-like systems.
Example 2 Numerical and tabular analysis
Install the optional packages in your environment:
python -m pip install numpy pandas matplotlib requestsThen run:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
scores = np.array([70, 80, 90])
print(scores.mean())
print((scores + 5).tolist())
frame = pd.DataFrame({"name": ["Ali", "Sara", "Bilal"],
"score": scores})
print(frame.loc[frame["score"] >= 80, "name"].tolist())
fig, axis = plt.subplots()
axis.bar(frame["name"], frame["score"])
axis.set_ylabel("Score")
axis.set_title("Student scores")
fig.tight_layout()
fig.savefig("student_scores.png")
plt.close(fig)Expected output: 80.0, [75, 85, 95], and ['Sara', 'Bilal']. The program creates or replaces student_scores.png. NumPy adds 5 element by element, pandas selects rows, and Matplotlib draws a labeled chart.
Example 3 A Requests call
Internet access and Requests are required. The endpoint's response is external and may change.
import requests
try:
response = requests.get("https://httpbin.org/get", timeout=10)
response.raise_for_status()
data = response.json()
print(data["url"])
except (requests.RequestException, ValueError, KeyError) as error:
print("Request failed:", error)On success the URL is printed. A network failure, unsuccessful HTTP status, invalid JSON, or missing field produces the failure message. The timeout prevents an indefinite wait for connection or response inactivity; it is not a universal total download deadline.
Student tasks
1. Use datetime to add 14 days to a chosen date and serialize the result as JSON.
2. Use NumPy to find the minimum, maximum, and average of five scores.
3. Use pandas to select scores above their mean and save those records to CSV without the DataFrame index.
4. Create a labeled chart for the five scores. Optional: run the HTTP example and record either the success output or its handled error.
Completion check: identify which imports needed installation and which came with Python.