The Core Rule

Theme: you are the stats crew for a school basketball team. Every example in this lesson builds a piece of the same season stats app, from a box score average to a scoreboard route.

Don’t rewrite code that already exists and has been tested. Find a library, read its API documentation, import it, and call its procedures.

import random                     # 1. import the library
jersey = random.randint(1, 99)    # 2. call a procedure described in its API
print("Random jersey number:", jersey)

College Board Big Idea 3.14: Libraries

Learning Objective (AAP-3.D): Select appropriate libraries or existing code segments to use in creating new programs.

Essential Knowledge What it means
AAP-3.D.1 A software library contains procedures that may be used in creating new programs.
AAP-3.D.2 Existing code segments can come from internal or external sources, such as libraries or previously written code.
AAP-3.D.3 The use of libraries simplifies the task of creating complex programs.
AAP-3.D.4 An API (Application Program Interface) is a specification for how the procedures in a library behave and can be used.
AAP-3.D.5 Documentation for an API or library is necessary to understand its behaviors and how to use them.

1. LxD Cycle Process

Empathize: Students often write long code to do things Python can already do, such as random numbers, averages, dates, and JSON. When a teammate’s Flask project fails with ModuleNotFoundError, they also don’t know why it works on one computer but not another.

Define:

  • POV: CSP students need to know how to find, read, and use libraries because rewriting existing code wastes time and missing packages break shared projects.
  • Learning Goal: Students will import standard library modules, read API documentation to use their procedures, and explain how requirements.txt lists the external libraries a Python project needs.

Ideate:

  • HMW Question: How might we show students that the libraries they use in classroom work are the same ones that power Open Coding Society?
  • Theme: Every example is part of one season stats app, so students see the same data move from a box score to a web route to a report.
  • Activity: Three short cycles of a tech talk followed by a code runner exercise. Follwed by an ending with a homework challenge that combines several libraries.

Prototype & Test: Add notes from your trial run with your project team here.


2. Lesson Plan

Learning Objective: By the end of this lesson, you will be able to import Python libraries, use API documentation to call their procedures correctly, and read a requirements.txt file.

Success Criteria: You can complete a program using procedures from at least three libraries and explain which libraries a project must install.

Cycle Tech Talk (1-2 min) Popcorn Hack (5 min)
1 What is a library? APIs and documentation Box score math with math and random
2 Libraries in Open Coding Society Serve the score from a Flask route
3 pip install and a projects requirements.txt (no hack, see the install snippet)
Homework   Build a Season Stats Report

Before the homework, use the Reference Guide for vocabulary and library lookups, and read the Code Example.


Cycle 1 Tech Talk: What is a Library? (2 minutes)

A library is a collection of procedures that someone already wrote and tested. In Python, one file of reusable code is called a module, and a group of modules is a package.

Python comes with a standard library, so modules like math, random, datetime, statistics, and json are ready to use with no installing.

Three ways to import:

import math                     # use as math.sqrt(144)
from random import randint      # use as randint(1, 99)
import statistics as stats      # use as stats.mean([24, 18, 31])

A library procedure is still a procedure. You already know how to write one (3.12 Calling Procedures and 3.13 Developing Procedures). Here is an average written by hand:

def calculate_average(points):
    total = 0
    for game in points:
        total += game
    return total / len(points)

print("Points per game:", calculate_average([24, 18, 31, 27, 22]))

Break that procedure into the three parts you have already studied:

Part In calculate_average In statistics.mean
Name and parameters calculate_average(points) mean(data)
Algorithm inside the loop that adds, then divides a tested algorithm you never see
Return value total / len(points) the average of the data
import statistics
print("Points per game:", statistics.mean([24, 18, 31, 27, 22]))

Both do the same job. The library version is one line, is already tested, and handles cases your loop does not, such as an empty list.

  • ✅ Do this: average = statistics.mean(points)
  • ❌ Don’t do this: write your own loop to add and divide when a tested procedure already exists

How do you know what a procedure does? You read its API, which tells you the procedure’s name, its parameters, and what it returns. You don’t need to know how random.randint works inside. You only need to know it returns a random integer between a and b, including both. That is abstraction: the algorithm is hidden, the API is what you use.

Where is the documentation? Look at docs.python.org, or ask Python directly:

Question Code
What is inside this library? dir(math)
What does this procedure do? help(math.sqrt) or print(math.sqrt.__doc__)

On the AP Exam: Libraries in College Board Pseudocode

The AP exam uses pseudocode instead of Python. Here is the same average procedure from above, written the College Board way.

Notice two kinds of procedures:

  • LENGTH, APPEND, and DISPLAY come from the AP reference sheet. They are built in, like a library, so you call them without writing them.
  • average is existing code. You write it once, then reuse it, which is exactly what AAP-3.D.2 means by “previously written code.”
PROCEDURE average(numbers)
{
   total ← 0
   FOR EACH num IN numbers
   {
      total ← total + num
   }
   RETURN(total / LENGTH(numbers))
}

points ← [24, 18, 30]
DISPLAY("Average points: " + average(points))

APPEND(points, 36)
DISPLAY("Games played: " + LENGTH(points))
DISPLAY("New average: " + average(points))

Output:

Average points: 24
Games played: 4
New average: 27

RANDOM(a, b) is also on the reference sheet. It works the same way as Python’s random.randint(a, b).

Popcorn Hack 1: Read the API, Then Use It (5 minutes)

The cell below prints the documentation for two procedures, then uses four of them on a box score. Read the printed docs first: they tell you the parameters and the return value, which is all you need to use a library.

Task: Run it. Then change the jersey range to 1-55, take the square root of a different court size, and predict the new output before you run it again.

Code Runner Challenge

Run it, then change the rehearsal range to 1-12 and predict the new output

View IPYNB Source
# CODE_RUNNER: Run it, then change the rehearsal range to 1-12 and predict the new output

import math
import random

# Read the API before calling a procedure
print("random.randint:", random.randint.__doc__)
print("math.ceil:", math.ceil.__doc__)
print()

rehearsal_scores = [8, 7, 10, 9, 8]

# random.choice picks one rehearsal to review
print("Rehearsal to review:", random.choice(rehearsal_scores), "out of 10")

# random.randint(a, b) returns a whole number from a to b, including both
studio_number = random.randint(1, 9)
print("Random studio number:", studio_number)

# math.sqrt returns the square root, so a 144 square foot practice space is this wide
side = math.sqrt(144)
print("Square practice space side:", side, "feet")

# math.ceil rounds up to the next whole number
average = sum(rehearsal_scores) / len(rehearsal_scores)
rounded_up = math.ceil(average)
print("Rehearsal average:", average, "-> rounded up:", rounded_up)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Cycle 2 Tech Talk: Libraries in Open Coding Society (2 minutes)

The libraries you are learning are not just for practice. They run the Open Coding Society website and backend.

This website (the pages repo) is written in Jupyter notebooks. A Python script called scripts/convert_notebooks.py uses libraries to turn every .ipynb into a page:

Library What it does How OCS uses it
nbformat Reads and writes notebook files Opens each lesson .ipynb
nbconvert Converts notebooks to other formats Turns notebooks into Markdown posts
pyyaml Reads YAML front matter Reads the title, permalink, and categories at the top of lessons

The Flask backend that handles logins, grades, and the code runner uses:

Library What it does How OCS uses it
Flask Builds web servers and APIs Runs the whole backend
Flask_Login, PyJWT Handles users and login tokens Signs you in and keeps you logged in
SQLAlchemy Talks to a database with Python objects Stores users, sections, and grades
python-dotenv Loads secret settings from a .env file Keeps passwords out of the code
pandas, scikit-learn Data tables and machine learning Grade prediction in model/grade_model.py

Key idea: the backend you use every day is a Flask app. Every OCS feature is a small procedure with a web address attached, called a route. When you log in, post a microblog, or press Run on a code cell, your browser calls a route like this one:

@app.route("/score")
def score():
    return jsonify({"home": 58, "away": 52})

In the next hack you will write one yourself. Flask and jsonify came from a library that someone installed with pip, which is where cycle 3 picks up.

Popcorn Hack 2: Write a Flask Route (5 minutes)

The OCS backend is built with Flask, the library from the table above. A Flask route is just a procedure with a web address on top of it.

Piece What it does
app = Flask(__name__) Creates the app, once per project
@app.route("/score") Says “run the procedure below when someone visits /score”
jsonify({...}) Turns a Python dictionary into the JSON a website receives
client.get("/score") Visits the address without needing a browser, so it works here

Task: Run it to see both routes answer. Then put your own players in the roster, and copy the pattern to add a route of your own, such as /coach or /record. Routes have to be defined above app.test_client().

Code Runner Challenge

Run it, then change the dancers and add a route of your own, such as /choreographer

View IPYNB Source
# CODE_RUNNER: Run it, then change the dancers and add a route of your own, such as /choreographer

from flask import Flask, jsonify

app = Flask(__name__)

# A route is a procedure with a web address attached to it
@app.route("/score")
def score():
    return jsonify({"routine": "Midnight Train", "energy": 9, "count": 8})

@app.route("/roster")
def roster():
    return jsonify({"dancers": ["Maya", "Jordan", "Sofia"]})

@app.route("/next-rehearsal")
def next_rehearsal():
    return jsonify({"studio": "B", "time": "4:30 PM", "focus": "clean the ending"})

# test_client visits the addresses without needing a browser
client = app.test_client()

print("/score says:", client.get("/score").get_json())
print("/roster says:", client.get("/roster").get_json())
print("/next-rehearsal says:", client.get("/next-rehearsal").get_json())
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Cycle 3 Tech Talk: pip and requirements.txt (2 minutes)

Standard library modules come with Python. External libraries like Flask and pandas do not, so you install them with pip.

A project lists the libraries it needs in a file called requirements.txt, one per line:

Flask
SQLAlchemy
pandas
python-dotenv

How to install them. Run this in your terminal, in the project folder. The venv gives the project its own private set of libraries:

python3 -m venv venv              # create the environment, once per project
source venv/bin/activate          # turn it on (Windows: venv\Scripts\activate)
pip install -r requirements.txt   # install everything in the file

That last command is how every OCS project gets its libraries, including the Flask backend. A real version of your team stats app would list Flask in its own requirements.txt the same way.

Why use a venv?

  • Each project gets its own libraries. One project can use an old version of Flask while another uses a new one, and they never clash.
  • You don’t break your computer’s Python. Installing into a venv can’t mess up anything else on your machine.
  • Teammates get the same setup. Anyone can delete the venv folder and rebuild it with the same three commands.
  • You can see what a project needs. Only the libraries from requirements.txt are inside, so a missing one shows up right away instead of working by accident.

Two things to remember:

  • Commit requirements.txt, never the venv folder. A teammate rebuilds it with the command above.
  • The name you pip install is not always the name you import: python-dotenv is import dotenv, scikit-learn is import sklearn, PyJWT is import jwt.

A ModuleNotFoundError usually means you skipped pip install -r requirements.txt, or your venv is not active.



3. Reference Guide

Key Vocabulary

Term Definition Example
Library A collection of procedures someone already wrote and tested math
Module One file of reusable Python code random.py
Package A group of modules installed together flask
API The specification for how a library’s procedures behave and are called randint(a, b) returns a whole number from a to b
Documentation The written description of an API docs.python.org
Standard library Libraries that come with Python, no install needed math, random, json
External library A library you have to install first Flask, pandas
pip The tool that installs external libraries pip install flask
requirements.txt The file listing the external libraries a project needs Flask on its own line
Virtual environment (venv) A private set of libraries for one project python3 -m venv venv

Standard Library Quick Reference

Every library below is already installed, so you only need to import it.

Library Use it for Example call Returns
math Math that is not built in math.sqrt(144) 12.0, the side of a 144 sq ft court
random Random numbers and picks random.randint(1, 99) a jersey number from 1 to 99
statistics Averages and spread statistics.mean([24, 18]) 21, the points per game
datetime Dates and days between them date(2026, 10, 15) - date.today() a timedelta, use .days for days until the next game
json Turning data into text and back json.dumps(player, indent=2) a JSON string a scoreboard page can read

4. Code Examples

Three Ways to Import

Each import style changes how you call the procedure. That is the only difference. All three lines here are pregame math for the stats app.

Code Runner Challenge

Run it, then change the dancer nickname to "M" and fix the line that breaks

View IPYNB Source
# CODE_RUNNER: Run it, then change the dancer nickname to "M" and fix the line that breaks

import math                    # import the whole library
from random import randint     # import one procedure out of a library
import statistics as stats     # import the library under a shorter nickname

# The whole library was imported, so the math. prefix is required
print("Studio circle distance:", round(2 * math.pi * 3, 2), "feet")

# randint was imported by name, so it is called with no prefix
print("Warm-up playlist number:", randint(1, 12))

# stats is a nickname that stands in for statistics
print("Rehearsal average:", stats.mean([8, 7, 10]))
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

5. Hacks & Practice Tasks

Prepare your submission IPYNB

Complete this quick-start flow so you can begin in about 2 minutes.

  1. Create a new notebook in your portfolio homework area: _notebooks/homework.
  2. Add one raw cell at the top with the frontmatter below.
  3. Add a code cell for each Popcorn Hack and the Homework. Keep the # CODE_RUNNER: comment as the first line of each code cell.
  4. Run each cell and check the output before submitting.
  5. Paste these lines into the description box when you submit:
Lesson: CSP 3.14 Libraries
Popcorn 1: what I changed = <your change>
Popcorn 2: my extra route = <your route address>
Homework: libraries used = <three module names>
Homework: days until my next game = <value>
---
layout: post
title: 3.14 Libraries HW
categories: [Python]
lesson_language: Python
lesson_topic: Libraries HW
lesson_part: interactive
lesson_type: lesson
permalink: /python/libraries-hw
author: githubID
---

Submission Safety Rules (Read First)

[!IMPORTANT] To avoid grading errors, follow these rules exactly:

  • Keep the # CODE_RUNNER: comment as the first line of each submission cell.
  • Your code must run in the code runner with no errors.
  • Only import standard library modules (such as math, random, statistics, datetime, json), or flask. Other installed packages, such as pandas, are not available in the code runner.
  • Do not use input(). The code runner cannot type answers for you.

Homework Hack: Dance Crew Showcase Report

The cell below is a worked example: a finished program that reports on Midnight Motion Crew’s showcase performances using six standard-library modules. Run it, read how each library is used, then build your own version in your homework notebook.

Your version must:

  1. Use at least 3 standard library modules. This one uses json, datetime, and statistics, plus csv, io, math, and random for extra credit.
  2. Have a procedure like summarize_season that returns the total performance points, average points, best performance, and points earned at each venue.
  3. Document your API. Write a docstring giving the parameters and the return value, so someone else could use your procedure without reading the code.
  4. Use datetime to report how many days are left until your next showcase.
  5. Write a requirements.txt. Imagine a real version of this app that uses pandas for the performance table and Flask for the scoreboard page. List those packages, and add a comment explaining why json and datetime are not listed.
  6. Extra credit: Add a validation check, export a CSV season card, calculate rehearsal blocks with math, and print a supportive randomized coach note.

Use your own dance crew, styles, venues, performances, and next showcase date. Any dance genre works: hip-hop, jazz, contemporary, ballet, breaking, or freestyle.

Code Runner Challenge

Run it, then replace the sample dancers, performances, and next showcase date

View IPYNB Source
# CODE_RUNNER: Run it, then replace the sample dancers, performances, and next showcase date

import csv
import io
import json
import math
import random
import statistics
from datetime import date

performances = [
    {"date": "2026-09-14", "venue": "Riverside Arts Night", "points": 24, "minutes": 28, "style": "hip-hop"},
    {"date": "2026-09-15", "venue": "Makerspace Showcase", "points": 18, "minutes": 22, "style": "jazz"},
    {"date": "2026-09-15", "venue": "Riverside Arts Night", "points": 31, "minutes": 30, "style": "contemporary"},
    {"date": "2026-09-16", "venue": "Roosevelt Open Mic", "points": 27, "minutes": 26, "style": "freestyle"},
]


def summarize_season(season):
    """
    Summarize a dance crew's performances.

    Parameters:
        season: list of dictionaries with date, venue, points, minutes, and style
    Returns:
        dictionary with total_points, average_points, best_game,
        points_by_opponent, and best_style
    """
    if not season:
        raise ValueError("season must contain at least one performance")

    points = [performance["points"] for performance in season]

    points_by_opponent = {}
    for performance in season:
        venue = performance["venue"]
        points_by_opponent[venue] = points_by_opponent.get(venue, 0) + performance["points"]

    best_performance = max(season, key=lambda performance: performance["points"])
    return {
        "total_points": sum(points),
        "average_points": round(statistics.mean(points), 1),
        "best_game": max(points),
        "points_by_opponent": points_by_opponent,
        "best_style": best_performance["style"],
    }


report = summarize_season(performances)

# Subtracting two dates returns a timedelta, and .days is the whole number of days
next_showcase = date(2026, 10, 15)
report["days_until_next_showcase"] = (next_showcase - date.today()).days
report["crew_note"] = "Small steps, full-out finish, and trust the count."

print("MIDNIGHT MOTION CREW REPORT")
print(json.dumps(report, indent=2))

# Extra credit: turn a performance length into eight-count rehearsal blocks.
longest_performance = max(performance["minutes"] for performance in performances)
report["rehearsal_blocks_for_longest_piece"] = math.ceil(longest_performance / 8)

# Extra credit: choose a supportive message without asking for input.
encouragements = [
    "Your timing is getting sharper.",
    "The transition into the final pose is strong.",
    "Keep the energy honest and enjoy the music.",
]
print("Coach note:", random.choice(encouragements))
print("Eight-count blocks for longest piece:", report["rehearsal_blocks_for_longest_piece"])

# Extra credit: create a CSV season card from the same data.
season_card = io.StringIO()
writer = csv.DictWriter(season_card, fieldnames=["date", "venue", "style", "points"])
writer.writeheader()
writer.writerows(
    {key: performance[key] for key in ["date", "venue", "style", "points"]}
    for performance in performances
)
print("\nCSV season card:")
print(season_card.getvalue().strip())

assert report["total_points"] == 100
assert report["best_game"] == 31
assert report["days_until_next_showcase"] == 15

# requirements.txt lists only external packages. json, datetime, statistics,
# random, math, csv, and io come with Python, so they are never listed.
requirements_txt = """pandas
Flask
"""
print("requirements.txt:")
print(requirements_txt)
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

6. Grading Plan (1 Point Total)

Classroom Rubric

  • 0.2 points: Popcorn completion (0.1 each) Student submitted their own changed version of Popcorn Hacks 1 and 2, and each cell runs without errors.
  • 0.8 points: Homework completion
    • 0.2 libraries: Imports and uses at least 3 standard library modules.
    • 0.2 procedure: summarize_season returns total points, average points, best game, and points per opponent.
    • 0.2 API documentation: The docstring describes the parameters and the return value.
    • 0.1 datetime: The report includes days until a chosen game date.
    • 0.1 requirements.txt: Lists pandas and Flask, and explains why standard library modules are not listed.

Quick Validation Checklist

  • Present: # CODE_RUNNER: comment as the first line of each cell.
  • Present: at least 3 different import statements from the standard library.
  • Present: a docstring on summarize_season giving the parameters and the return value.
  • Present: json.dumps output showing the report.
  • Absent: input(), external package imports, and errors when run.

7. References

College Board. (2023). AP Computer Science Principles course and exam description [Effective fall 2023]. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-course-and-exam-description.pdf

College Board. (2023). AP Computer Science Principles exam reference sheet. https://apcentral.collegeboard.org/media/pdf/ap-computer-science-principles-exam-reference-sheet.pdf

Pallets. (n.d.). Flask documentation: Quickstart. Retrieved September 23, 2026.

Python Packaging Authority. (n.d.). Requirements file format. pip documentation. Retrieved September 23, 2026.

Python Software Foundation. (n.d.). The Python standard library. Python 3 documentation. Retrieved September 23, 2026.

Submit Assignment

Click to upload or drag and drop
PDF, ZIP, images, or documents (Max 10MB per file)