Python 3.14: Libraries HW
Python 3.14 Libraries
This notebook covers both Popcorn Hacks and the Season Stats Report Homework Hack with API documentation and a requirements.txt example.
Popcorn Hack 1: Read the API, Then Use It
The jersey_number range is changed to 1–55, and the square-court example uses 225, so the deterministic square-root result is 15.0. The random game and jersey_number can vary on each run.
Code Runner Challenge
3.14 Popcorn 1 - use math and random APIs
View IPYNB Source
# CODE_RUNNER: 3.14 Popcorn 1 - use math and random APIs
import math
import random
# API docstrings show what arguments these procedures accept and what they return.
print("random.randint:", random.randint.__doc__)
print("math.sqrt:", math.sqrt.__doc__)
print()
match_points = [24, 18, 31, 27, 22]
# random.choice can select any game, so this output is intentionally not predictable exactly.
print("Random game to review:", random.choice(match_points), "points")
# The changed range allows every whole-number jersey_number from 1 through 55, inclusive.
jersey_number = random.randint(1, 55)
print("Random jersey_number number (1-55):", jersey_number)
# A 225-square-foot square has side length 15 feet.
side = math.sqrt(225)
print("Square court side:", side, "feet")
# math.ceil rounds the calculated average upward to a whole number.
average = sum(match_points) / len(match_points)
print("Points per game:", average, "-> rounded up:", math.ceil(average))
Popcorn Hack 2: Write a Flask Route
The roster is customized and a new /coach route follows the same Flask route pattern as /score and /roster.
Code Runner Challenge
3.14 Popcorn 2 - customize Flask routes with a browser-safe fallback
View IPYNB Source
# CODE_RUNNER: 3.14 Popcorn 2 - customize Flask routes with a browser-safe fallback
# Try the real Flask version first so this still matches the lesson when Flask is installed.
# If Flask is missing locally, fall back to equivalent plain-Python route data so the cell still runs.
try:
from flask import Flask, jsonify
app = Flask(__name__)
# Each decorated procedure returns JSON when its matching address is requested.
@app.route("/score")
def score():
return jsonify({"home": 6, "away": 4, "set": 3})
@app.route("/roster")
def roster():
return jsonify({"players": ["Pranav", "Arya", "Deyar"]})
# This extra /coach route completes the lesson's customization task.
@app.route("/coach")
def coach():
return jsonify({"coach": "Coach Patel", "focus": "serve consistency"})
# test_client visits the routes without needing a separate browser window.
client = app.test_client()
print("/score says:", client.get("/score").get_json())
print("/roster says:", client.get("/roster").get_json())
print("/coach says:", client.get("/coach").get_json())
except ModuleNotFoundError:
# Local/Jupyter fallback: mirror the same route responses with dictionaries.
# This avoids a Flask import error while keeping the route names and returned data visible.
routes = {
"/score": {"home": 6, "away": 4, "set": 3},
"/roster": {"players": ["Pranav", "Arya", "Deyar"]},
"/coach": {"coach": "Coach Patel", "focus": "serve consistency"}
}
for route in ["/score", "/roster", "/coach"]:
print(route, "says:", routes[route])
Homework Hack: Tennis Season Stats Report
This version uses four standard-library modules: json, statistics, datetime, and math. The procedure documents its API and returns the required totals, average, best match, and points by opponent.
Code Runner Challenge
3.14 Homework - tennis season stats report
View IPYNB Source
# CODE_RUNNER: 3.14 Homework - tennis season stats report
import json
import math
import statistics
from datetime import date
# Each dictionary is one tennis match from the season report.
season_matches = [
{"date": "2026-09-05", "opponent": "Westview", "points": 12, "minutes": 64},
{"date": "2026-09-12", "opponent": "Del Norte", "points": 15, "minutes": 71},
{"date": "2026-09-19", "opponent": "Westview", "points": 10, "minutes": 58},
{"date": "2026-09-26", "opponent": "Poway", "points": 18, "minutes": 83}
]
def build_season_summary(season):
"""Return summary statistics for a list of tennis-match dictionaries.
Parameters:
season: list of dictionaries containing date, opponent, points, and minutes.
Returns:
dictionary with total_points, average_points, top_match, and opponent_points.
"""
# statistics.mean and built-ins summarize the numeric results without rewriting tested library algorithms.
points = [game["points"] for game in season]
# Accumulate points under each opponent name so repeat opponents are combined.
opponent_points = {}
for game in season:
opponent = game["opponent"]
opponent_points[opponent] = opponent_points.get(opponent, 0) + game["points"]
return {
"total_points": sum(points),
"average_points": round(statistics.mean(points), 1),
"top_match": max(points),
"opponent_points": opponent_points
}
report = build_season_summary(season_matches)
# datetime subtracts dates; max keeps the report sensible even after the chosen date passes.
next_game = date(2026, 10, 15)
report["days_until_next_game"] = max(0, (next_game - date.today()).days)
# math is a fourth standard-library module; it rounds total playing time up to whole hours.
total_minutes = sum(game["minutes"] for game in season_matches)
report["practice_hours_equivalent"] = math.ceil(total_minutes / 60)
# json.dumps converts the Python dictionary into readable JSON text for a web-style report.
print(json.dumps(report, indent=2))
# requirements.txt lists only external packages; standard-library modules already come with Python.
requirements_txt = """pandas
Flask
# json, math, statistics, and datetime are standard-library modules, so they are not listed.
"""
print("\nrequirements.txt:\n" + requirements_txt)
requirements.txt
pandas
Flask
# json, math, statistics, and datetime are standard-library modules, so they are not listed.
pandas and Flask would need installation in a real external-library version of the project; the other modules ship with Python.