← Course Hub← 课程主页 ← All Units← 返回单元列表
H I G H  S C H O O L  C O M P U T E R  S C I E N C E
Solutions详解

Data, Databases and the Web · Solutions数据、数据库与网络 · 详解

Companion to the Practice Set · Mark-by-mark walkthroughs · AP CSP-Feeder / US / ON / BC / AB styles练习题配套详解 · 逐分讲解 · AP CSP 衔接 / 美 / 安 / 卑 / 阿省考风格

EASY MEDIUM HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC 🇨🇦 AB AP CSP-style MCQAP CSP 风格选择题 AP CSP-feeder FRQAP CSP 衔接简答题 ON Provincial-style安大略省考风格 BC Provincial-style卑诗省考风格 AB/Universal Applied阿省/通用应用题 Honors荣誉级


PART I  ·  SHORT RESPONSE  ·  SOLUTIONS第一部分  ·  短答题  ·  详解25 marks共 25 分
Q1 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §1 Data vs Information数据与信息 · CSTA 3A-DA-10 [3 marks][3 分]

A weather sensor records values with no labels. A program adds labels and displays an interpreted summary. Which statement best describes the relationship between the raw values and the final display?气象传感器记录了没有标签的值。程序添加标签并显示经解释的摘要。哪个陈述最准确地描述了原始值与最终显示之间的关系?

Answer: (B) - The raw values are data; the labelled, interpreted display is information.答案:(B) - 原始值是数据;经过标注和解释的显示是信息。

Eliminate each option: [1]逐一排除每个选项:[1]

(A) Incorrect. Being storable by a computer does not make values information. A number in memory with no context is still raw data.不正确。能被计算机存储并不使值成为信息。内存中没有上下文的数字仍然是原始数据。
(B) Correct. Raw sensor readings (22.4, 65, 1013.2) have no inherent meaning without labels or interpretation. Once a program adds column labels, units, and a derived conclusion ("expect rain"), the output carries meaning and becomes information. [1]正确。原始传感器读数(22.4、65、1013.2)在没有标签或解释的情况下没有固有含义。一旦程序添加列标签、单位和派生结论("预计有雨"),输出便携带含义并成为信息。[1]
(C) Incorrect. The final display is information, not data, because it includes context and interpretation.不正确。最终显示是信息,不是数据,因为它包含上下文和解释。
(D) Incorrect. Containing numbers does not make something data. The final display with labels and a conclusion is information. [1]不正确。包含数字并不使某物成为数据。带有标签和结论的最终显示是信息。[1]
Insight:解题洞察: The data-to-information transformation always requires context. AP CSP Big Idea 2 (DAT) opens with exactly this principle: data communicates raw facts; programs process those facts into knowledge (information). On any exam, ask yourself: "Does this value carry meaning without extra context?" If not, it is data.数据到信息的转换始终需要上下文。AP CSP 大概念 2(DAT)就以这个原则开篇:数据传达原始事实;程序将这些事实处理成知识(信息)。在任何考试中,问自己:"这个值没有额外上下文能传达含义吗?"如果不能,它就是数据。
Q2 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §2 File Input/Output文件读写 · CSE2130 1.4.2 [3 marks][3 分]

A student wants to add a new log entry to log.txt without erasing existing entries. Which file-open mode?学生想向 log.txt 添加新日志条目而不删除现有条目。哪种文件打开模式?

Answer: (C) - "a" (append mode)答案:(C) - "a"(追加模式)

Four Python file modes: [1]四种 Python 文件模式:[1]

(A) "r" = read-only. The file cannot be written to. Incorrect."r" = 只读。无法写入文件。不正确。
(B) "w" = write mode. Opens the file and erases all existing content before writing. Incorrect for this task. [1]"w" = 写入模式。打开文件并在写入前删除所有现有内容。不适合此任务。[1]
(C) "a" = append mode. Opens the file and positions the write cursor at the end, so new content is added after existing content. Correct. [1]"a" = 追加模式。打开文件并将写入游标定位在末尾,因此新内容添加到现有内容之后。正确。[1]
(D) "x" = exclusive create. Creates a new file; raises an error if the file already exists. Incorrect."x" = 独占创建。创建新文件;如果文件已存在则引发错误。不正确。
Insight:解题洞察: The keyword phrase on exams is "without erasing" or "add to the end" - both signal append mode "a". If the question says "overwrite" or "start fresh," the answer is write mode "w". AB CSE2130 outcome 1.4.4 ("exporting data to a file") directly tests this choice.考试中的关键词是"不删除"或"添加到末尾",两者都表示追加模式 "a"。如果题目说"覆盖"或"重新开始",答案是写入模式 "w"。AB CSE2130 结果 1.4.4("将数据导出到文件")直接考查这个选择。
Q3 EASY 🇨🇦 ON ON Provincial-style安大略省考风格 §3 CSV and Structured DataCSV 与结构化数据 · ICS4U A3.1 [4 marks][4 分]

CSV with a header row and three product records. Identify the header row and record count; explain a crash when computing price * 1.13.CSV 包含标题行和三条产品记录。指出标题行和记录数;解释计算 price * 1.13 时崩溃的原因。

Part (a): Header row = product_id,name,price; 3 records. Part (b): CSV values are strings; fix with float(row["price"]) * 1.13.第 (a) 部分:标题行 = product_id,name,price;3 条记录。第 (b) 部分:CSV 值为字符串;修复:float(row["price"]) * 1.13

Part (a)第 (a) 部分

The header row is the first line of the CSV that names each column: product_id,name,price. [1] The three subsequent lines (101, 102, 103) are data rows (records), so the file contains 3 records. [1]标题行是 CSV 的第一行,命名每一列:product_id,name,price[1]随后的三行(101、102、103)是数据行(记录),因此文件包含 3 条记录。[1]

Part (b)第 (b) 部分

The most likely cause: every value read from a CSV is a string. row["price"] holds the string "3.50". Python 3 raises a TypeError when multiplying a string by a float ("3.50" * 1.13 is not defined). [1]最可能的原因:从 CSV 读取的每个值都是字符串。row["price"] 保存字符串 "3.50"。Python 3 在字符串乘以浮点数时引发 TypeError"3.50" * 1.13 未定义)。[1]

Fix (one line):修复(一行):

float(row["price"]) * 1.13

float(row["price"]) converts the string "3.50" to the floating-point number 3.50, which can then be multiplied. [1]float(row["price"]) 将字符串 "3.50" 转换为浮点数 3.50,然后可以进行乘法运算。[1]

Insight:解题洞察: This is the single most common CSV bug. Always convert numeric CSV fields before arithmetic: use int() for whole numbers, float() for decimals. The Study Guide's Exam Strategy section lists this as the top CSV pitfall. If the question says "the program crashes" on a CSV numeric operation, the answer is almost always a missing type conversion.这是最常见的 CSV 错误。在算术运算前始终转换数值型 CSV 字段:整数用 int(),小数用 float()。学习指南的考试策略部分将此列为 CSV 的首要陷阱。如果题目说程序在 CSV 数值操作上"崩溃",答案几乎总是缺少类型转换。
Q4 MEDIUM 🇨🇦 AB AB/Universal Applied阿省/通用应用题 §2 File Input/Output文件读写 · CSE2130 1.4.4 / 1.4.5 [7 marks][7 分]

Python program reads scores from scores.txt, computes average, writes to summary.txt.Python 程序从 scores.txt 读取成绩,计算平均值,写入 summary.txt

Parts (a)-(d): See rationale below.第 (a)-(d) 部分:见下方详解。

Part (a) - Contents of summary.txt第 (a) 部分 - summary.txt 的内容

The scores are 87, 92, 74, 95, 88. Count = 5. Sum = 87+92+74+95+88 = 436. Average = 436/5 = 87.2. The file contains exactly:成绩为 87、92、74、95、88。Count = 5。Sum = 87+92+74+95+88 = 436。Average = 436/5 = 87.2。文件内容恰好为:

Count: 5
Average: 87.2

The :.1f format specifier rounds to 1 decimal place. [1] Both lines end with \n (newline). [1]:.1f 格式说明符保留 1 位小数。[1]两行均以 \n(换行符)结尾。[1]

Part (b) - line.strip()第 (b) 部分 - line.strip()

line.strip() removes leading and trailing whitespace, including the newline character (\n) that appears at the end of each line in the file. [1] Without it, int("87\n") would raise a ValueError because the newline makes the string invalid for integer conversion. [1]line.strip() 删除首尾空白字符,包括文件每行末尾的换行符(\n)。[1]如果没有它,int("87\n") 会引发 ValueError,因为换行符使字符串对整数转换无效。[1]

Part (c) - Append "Max: 95"第 (c) 部分 - 追加 "Max: 95"

with open("summary.txt", "a") as f:
    f.write("Max: 95\n")

Mode "a" opens the existing file and positions the cursor at the end. [1] f.write("Max: 95\n") adds the line without touching existing content. [1]模式 "a" 打开现有文件并将游标定位在末尾。[1]f.write("Max: 95\n") 添加该行而不影响现有内容。[1]

Part (d) - with block auto-close第 (d) 部分 - with 块自动关闭

The with statement is a context manager: when execution leaves the block (normally or via an exception), Python automatically calls the file's close method, flushing any buffered data and releasing the OS file handle. [1]with 语句是一个上下文管理器:当执行离开代码块时(正常或通过异常),Python 自动调用文件的关闭方法,刷新所有缓冲数据并释放操作系统文件句柄。[1]

Insight:解题洞察: The three operations every file question tests are open-read/write-close. The with block automates the close step and is Python best practice. On a CSE2130 exam, always use the with pattern in your answers; manually calling f.close() at the end is also acceptable but the with approach is safer under errors.每道文件题考查的三个操作是打开-读取/写入-关闭。with 块自动化了关闭步骤,是 Python 最佳实践。在 CSE2130 考试中,答案中始终使用 with 模式;在末尾手动调用 f.close() 也可接受,但 with 方法在出错时更安全。
Q5 MEDIUM 🇨🇦 BC BC Provincial-style卑诗省考风格 §3 CSV and Structured DataCSV 与结构化数据 · CSTA 3A-DA-11 [8 marks][8 分]

Program reads students.csv with csv.DictReader and prints students who scored above 85.程序使用 csv.DictReader 读取 students.csv,打印成绩高于 85 的学生。

Parts (a)-(d): See rationale below.第 (a)-(d) 部分:见下方详解。

Part (a) - Output第 (a) 部分 - 输出

Check each student: Alice 92 > 85 (print), Bob 78 not > 85 (skip), Carol 95 > 85 (print), David 82 not > 85 (skip), Eve 88 > 85 (print). Exact output: [2]检查每位学生:Alice 92 > 85(打印),Bob 78 不 > 85(跳过),Carol 95 > 85(打印),David 82 不 > 85(跳过),Eve 88 > 85(打印)。精确输出:[2]

Alice 92
Carol 95
Eve 88

Part (b) - DictReader vs reader第 (b) 部分 - DictReader 与 reader

csv.reader returns each row as a plain list (e.g., ["Alice", "11", "92"]); fields are accessed by numeric index (row[2]). [1] csv.DictReader reads the header row automatically and maps each subsequent row to a dictionary keyed by column name (e.g., {"name": "Alice", "grade": "11", "score": "92"}). Advantage: fields are accessed by name (row["score"]), making the code self-documenting and less prone to off-by-one index errors. [1]csv.reader 将每行作为普通列表返回(例如 ["Alice", "11", "92"]);字段通过数字索引访问(row[2])。[1]csv.DictReader 自动读取标题行,并将后续每行映射为以列名为键的字典(例如 {"name": "Alice", "grade": "11", "score": "92"})。优点:通过名称访问字段(row["score"]),使代码自文档化,减少索引偏移错误。[1]

Part (c) - Type conversion第 (c) 部分 - 类型转换

CSV values are always strings. row["score"] holds "92" (a string), not 92 (an integer). Comparing a string to an integer with > raises a TypeError in Python 3 ("92" > 85 is invalid). [1] int(row["score"]) converts "92" to 92 first, making the comparison valid. [1]CSV 值始终是字符串。row["score"] 保存 "92"(字符串),而不是 92(整数)。在 Python 3 中,用 > 比较字符串和整数会引发 TypeError"92" > 85 无效)。[1]int(row["score"]) 先将 "92" 转换为 92,使比较有效。[1]

Part (d) - Modified condition第 (d) 部分 - 修改条件

if int(row["score"]) > 85 and int(row["grade"]) == 12:

Both score and grade must be converted to integers before numeric comparison. [1] Using and combines both conditions: score above 85 AND grade exactly 12. Only Carol (grade 12, score 95) meets both conditions. [1]在数值比较前,scoregrade 都必须转换为整数。[1]使用 and 组合两个条件:成绩高于 85 且年级恰好为 12。只有 Carol(12 年级,成绩 95)同时满足两个条件。[1]

Insight:解题洞察: When filtering on multiple CSV columns, each numeric field needs its own type conversion. A common exam trap is to convert one field but forget the other. Always scan all >, <, and == comparisons against CSV-sourced values and ask: "Was this converted?"对多个 CSV 列进行过滤时,每个数值字段都需要自己的类型转换。常见考试陷阱是转换一个字段但忘记另一个。始终扫描所有与 CSV 来源值的 ><== 比较,并问:"这个被转换了吗?"
PART II  ·  EXTENDED RESPONSE  ·  SOLUTIONS第二部分  ·  简答题  ·  详解31 marks共 31 分
Q6 MEDIUM 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §4 Relational Databases and Tables关系数据库与表 · CSTA 3A-DA-10 [8 marks][8 分]

Library database with Books and Loans tables. Primary/foreign keys and normalisation.图书馆数据库,包含 Books 和 Loans 表。主键/外键和规范化。

Parts (a)-(c): See rationale below.第 (a)-(c) 部分:见下方详解。

Part (a) - Primary keys第 (a) 部分 - 主键

Books table primary key: book_id. Each book has a unique ID (1, 2, 3 - no duplicates). [1]Books 表主键:book_id。每本书有唯一的 ID(1、2、3 - 没有重复)。[1]

Loans table primary key: loan_id. Each loan event has a unique ID (1, 2, 3). [1]Loans 表主键:loan_id。每条借阅记录有唯一的 ID(1、2、3)。[1]

A column qualifies as a primary key when every row has a unique, non-null value in that column and the value never repeats across rows. [1]当每行在该列中具有唯一的非空值且值不在行间重复时,该列可作为主键。[1]

Part (b) - Foreign key第 (b) 部分 - 外键

The foreign key in Loans is book_id. [1] It references the book_id column in the Books table. [1] Linking via this foreign key allows a program to look up the full book details (title, author) for any loan: given a loan row with book_id = 2, the program can find the book "Data Science 101" in Books without repeating that title in every Loans row. [1]Loans 中的外键是 book_id[1]它引用 Books 表中的 book_id 列。[1]通过此外键链接允许程序查找任何借阅记录的完整图书详情(书名、作者):给定 book_id = 2 的借阅行,程序可以在 Books 中找到书目"Data Science 101",而无需在每条 Loans 行中重复该书名。[1]

Part (c) - Normalisation第 (c) 部分 - 规范化

Storing the title once in Books and referencing it by book_id in Loans is better because: (1) if the title needs to be corrected, it is changed in one place only; repeating it in every Loans row means every copy must be updated, risking inconsistency. (2) It saves storage space. [1] This principle is called normalisation. [1]将书名在 Books 中存储一次并在 Loans 中通过 book_id 引用更好,因为:(1) 如果书名需要更正,只需在一个地方更改;在每条 Loans 行中重复意味着必须更新每个副本,有不一致的风险。(2) 节省存储空间。[1]这个原则称为规范化[1]

Insight:解题洞察: On any "why use two tables?" question, the answer is always normalisation: store each piece of data once, reference by key. The counterargument (flat table / CSV) is simplicity - but simplicity loses when data needs to change or be queried across dimensions. AP CSP connects this to CSTA 3A-DA-10's "evaluate tradeoffs in how data elements are organized."在任何"为什么使用两个表?"问题中,答案总是规范化:每条数据存储一次,通过键引用。反驳(平面表/CSV)是简单性,但当数据需要更改或跨维度查询时,简单性就失去了优势。AP CSP 将此与 CSTA 3A-DA-10 的"评估数据元素组织方式的权衡"联系起来。
Q7 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §5 SQL BasicsSQL 基础 · ICS4C A2.2 [8 marks][8 分]

SQL queries on the Books and Loans tables from Q6.对 Q6 的 Books 和 Loans 表执行 SQL 查询。

Parts (a)-(e): See rationale below.第 (a)-(e) 部分:见下方详解。

Part (a) - All columns from Books第 (a) 部分 - Books 表所有列

SELECT * FROM Books;

SELECT * returns all columns; FROM Books names the table. [1]SELECT * 返回所有列;FROM Books 指定表名。[1]

Part (b) - title and author where book_id = 2第 (b) 部分 - book_id = 2 的 title 和 author

SELECT title, author FROM Books WHERE book_id = 2;

Result: Data Science 101 | Lee, C. [2] (1 mark for SELECT+FROM, 1 mark for WHERE clause)结果:Data Science 101 | Lee, C. [2](1 分给 SELECT+FROM,1 分给 WHERE 子句)

Part (c) - All Loans sorted by due_date ascending第 (c) 部分 - 所有 Loans 按 due_date 升序排序

SELECT * FROM Loans ORDER BY due_date ASC;

The keyword for ascending sort order is ASC (it is also the default, so ORDER BY due_date without ASC also works). [2]升序排列的关键字是 ASC(它也是默认值,所以不带 ASCORDER BY due_date 也有效)。[2]

Part (d) - Error and correction第 (d) 部分 - 错误和更正

Error: SELECT title WHERE book_id = 1; is missing the FROM Books clause. SQL requires FROM to identify the table. [1]错误:SELECT title WHERE book_id = 1; 缺少 FROM Books 子句。SQL 需要 FROM 来标识表。[1]

SELECT title FROM Books WHERE book_id = 1;

Result: Python Primer. [1]结果:Python Primer[1]

Part (e) - Mandatory clause order第 (e) 部分 - 必须子句顺序

SELECTFROMWHEREORDER BY. [1]SELECTFROMWHEREORDER BY[1]

Insight:解题洞察: Missing FROM is the most common SQL error on Ontario exams. A complete SELECT always needs at minimum SELECT + FROM. The WHERE and ORDER BY clauses are optional additions, but their order relative to each other is fixed: WHERE filters before ORDER BY sorts. Write the clauses in order and you will never place ORDER BY before WHERE.缺少 FROM 是安大略考试中最常见的 SQL 错误。完整的 SELECT 至少需要 SELECT + FROM。WHERE 和 ORDER BY 子句是可选的添加项,但它们相对彼此的顺序是固定的:WHERE 在 ORDER BY 排序之前过滤。按顺序写子句,就永远不会把 ORDER BY 放在 WHERE 之前。
Q8 HARD 🇨🇦 BC 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §4 + §5 DB design + SQL analysis数据库设计 + SQL 分析 · CSTA 3A-DA-10 [8 marks][8 分]

Music streaming service. Students (student_id, name, plan) and Plays (play_id, student_id, song_title, play_count).音乐流媒体服务。Students(student_id, name, plan)和 Plays(play_id, student_id, song_title, play_count)。

Parts (a)-(c): See rationale below.第 (a)-(c) 部分:见下方详解。

Part (a) - Premium students alphabetically第 (a) 部分 - 按字母顺序的 premium 学生

SELECT name, plan
FROM Students
WHERE plan = 'premium'
ORDER BY name ASC;

[1] SELECT names the correct columns. [1] WHERE filters for plan = 'premium' (string comparisons in SQL use single quotes). [1] ORDER BY name ASC sorts alphabetically.[1] SELECT 命名正确的列。[1] WHERE 过滤 plan = 'premium'(SQL 中字符串比较使用单引号)。[1] ORDER BY name ASC 按字母排序。

Part (b) - Songs with play_count over 100, highest first第 (b) 部分 - play_count 大于 100 的歌曲,最高在前

SELECT song_title
FROM Plays
WHERE play_count > 100
ORDER BY play_count DESC;

[1] Correct column (song_title) and table (Plays). [1] WHERE play_count > 100 filters correctly (numeric, no quotes). [1] ORDER BY play_count DESC sorts highest first (DESC = descending).[1] 正确的列(song_title)和表(Plays)。[1] WHERE play_count > 100 正确过滤(数值,不加引号)。[1] ORDER BY play_count DESC 最高在前(DESC = 降序)。

Part (c) - Flat table vs linked tables tradeoff第 (c) 部分 - 平面表与关联表的权衡

Flat table: simpler to set up and query (one table, no joins); however, the student name is repeated in every Plays row, wasting storage and risking inconsistency if the name changes. [1]平面表:设置和查询更简单(一个表,无需连接);但是,学生姓名在每条 Plays 行中重复,如果姓名更改则浪费存储空间且有不一致风险。[1]

When student names might change, the two-table (linked) design is better: the name is stored once in Students; only the student_id foreign key appears in Plays. Updating the name requires changing only one row in Students, not every Plays row. [1]当学生姓名可能更改时,两表(关联)设计更好:姓名在 Students 中只存储一次;Plays 中只有 student_id 外键。更新姓名只需更改 Students 中的一行,而不是每条 Plays 行。[1]

Insight:解题洞察: SQL string literals always use single quotes: WHERE plan = 'premium' not double quotes. Numeric literals have no quotes: WHERE play_count > 100. Mixing these up is a common syntax error. Also note: DESC and ASC apply to the column in the ORDER BY clause, not to the whole query.SQL 字符串字面量始终使用单引号:WHERE plan = 'premium' 而不是双引号。数值字面量不加引号:WHERE play_count > 100。混淆这两者是常见的语法错误。另外:DESCASC 应用于 ORDER BY 子句中的列,而不是整个查询。
Q9 HARD Honors荣誉级 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §5 SQL COUNT + tradeoff analysisSQL COUNT + 权衡分析 · CSTA 3A-DA-10 / 3A-DA-12 [7 marks][7 分]

Scores table (score_id, student_id, subject, score). SQL COUNT, AND filter, and CSV-vs-database tradeoff.Scores 表(score_id、student_id、subject、score)。SQL COUNT、AND 过滤以及 CSV 与数据库的权衡。

Parts (a)-(c): See rationale below.第 (a)-(c) 部分:见下方详解。

Part (a) - COUNT CS rows第 (a) 部分 - COUNT CS 行数

SELECT COUNT(*) FROM Scores WHERE subject = 'CS';

COUNT(*) counts matching rows. [1] From the table: rows with CS are score_id 2 (student 1, CS, 88) and score_id 4 (student 3, CS, 95). Expected result: 2. [1]COUNT(*) 统计匹配行数。[1]从表中:CS 行为 score_id 2(学生 1,CS,88)和 score_id 4(学生 3,CS,95)。预期结果:2[1]

Part (b) - Math AND score >= 85第 (b) 部分 - Math 且 score >= 85

SELECT student_id, score
FROM Scores
WHERE subject = 'Math' AND score >= 85;

Checking the table: Math rows are (student_id=1, score=92) and (student_id=2, score=78). Only student 1 has Math score >= 85. [1] The AND operator requires both conditions to be true simultaneously. [1] Result: student_id = 1, score = 92.检查表:Math 行为(student_id=1, score=92)和(student_id=2, score=78)。只有学生 1 的 Math 成绩 >= 85。[1]AND 运算符要求两个条件同时为真。[1]结果:student_id = 1,score = 92。

Part (c) - CSV vs database tradeoff第 (c) 部分 - CSV 与数据库权衡

CSV advantage: simple to create, edit, and share; no database software required; any spreadsheet or text editor can read it. [1]CSV 优点:创建、编辑和共享简单;不需要数据库软件;任何电子表格或文本编辑器都可以读取。[1]

Relational database advantage: supports complex queries (WHERE, JOIN, COUNT, ORDER BY) across large datasets; enforces data integrity through primary/foreign keys; avoids data duplication through normalisation. [1]关系数据库优点:支持跨大型数据集的复杂查询(WHERE、JOIN、COUNT、ORDER BY);通过主键/外键强制数据完整性;通过规范化避免数据重复。[1]

Recommendation: a relational database for a school with 500 students and 10 subjects. With 500 students each having up to 10 subject scores, a single CSV would have up to 5000 rows with repeated student names and be difficult to query (e.g., "find all students with Math score above 80"). A database allows efficient SQL queries, avoids duplication, and scales cleanly. [1]建议:对于有 500 名学生和 10 门课程的学校,推荐使用关系数据库。500 名学生每人最多有 10 门课程成绩,单个 CSV 最多有 5000 行,学生姓名重复且难以查询(例如"找出所有数学成绩高于 80 的学生")。数据库允许高效的 SQL 查询,避免重复,并能整洁地扩展。[1]

Insight:解题洞察: CSTA 3A-DA-10 literally says "evaluate the tradeoffs." A full-mark answer always names a real advantage for each option before giving a recommendation. Saying "databases are better" without naming a CSV advantage is a partial-credit answer. The scale trigger is key: for small, static datasets CSV is fine; for hundreds of users or multi-dimensional queries, use a database.CSTA 3A-DA-10 明确说"评估权衡"。满分答案在给出建议之前总是为每个选项说出一个真实的优点。只说"数据库更好"而不说明 CSV 的优点只能得部分分。规模触发器是关键:对于小型静态数据集,CSV 就够了;对于数百个用户或多维查询,使用数据库。
PART III  ·  MODELING / APPLIED  ·  SOLUTIONS第三部分  ·  建模与应用  ·  详解25 marks共 25 分
Q10 MEDIUM 🇺🇸 US 🇨🇦 ON AP CSP-feeder FRQAP CSP 衔接简答题 §6 HTML and the WebHTML 与网络 · AB CSE1210 [8 marks][8 分]

HTML with errors; student builds a library catalogue page.包含错误的 HTML;学生构建图书馆目录页面。

Parts (a)-(c): See rationale below.第 (a)-(c) 部分:见下方详解。

Part (a) - Two errors第 (a) 部分 - 两个错误

Error 1: <title>Library Catalogue<title> - the closing tag is missing the slash. It should be </title>. A closing tag requires a forward slash before the tag name. [2]错误 1:<title>Library Catalogue<title> - 结束标签缺少斜杠。应为 </title>。结束标签在标签名前需要正斜杠。[2]

Error 2: <a href="books.html">Browse Books</p> - the anchor tag <a> is opened but never closed; instead a </p> appears. The correct closing is </a></p> (close the anchor inside the paragraph) or more commonly <p><a href="books.html">Browse Books</a></p>. Also, the <li>Data Science 101 item is missing its closing </li> tag (also acceptable as a second error). [2]错误 2:<a href="books.html">Browse Books</p> - 锚点标签 <a> 已打开但从未关闭;取而代之的是 </p>。正确的关闭方式是 </a></p>(在段落内关闭锚点),或更常见地 <p><a href="books.html">Browse Books</a></p>。另外,<li>Data Science 101 项缺少结束 </li> 标签(也可作为第二个错误)。[2]

Part (b) - HTML table第 (b) 部分 - HTML 表格

<table>
  <tr>
    <th>Title</th><th>Author</th>
  </tr>
  <tr>
    <td>Python Primer</td><td>Smith, J.</td>
  </tr>
  <tr>
    <td>Web Basics</td><td>Patel, R.</td>
  </tr>
</table>

Key tags: <table> wraps the table; <tr> = table row; <th> = header cell (bold, centred by default); <td> = data cell. [1] for correct table structure (table/tr); [1] for correct header row with th; [1] for both data rows with td.关键标签:<table> 包裹表格;<tr> = 表格行;<th> = 表头单元格(默认粗体居中);<td> = 数据单元格。[1]正确的表格结构(table/tr);[1]带 th 的正确标题行;[1]两个带 td 的数据行。

Part (c) - head vs body第 (c) 部分 - head 与 body

The <body> section contains the page's visible content (headings, paragraphs, tables, links). [1] An example of something in the <head> section: <title> (sets the browser tab title, not visible on the page itself), <meta charset="UTF-8"> (character encoding), or a CSS link.<body> 部分包含页面的可见内容(标题、段落、表格、链接)。[1]属于 <head> 部分的例子:<title>(设置浏览器标签标题,不在页面上显示)、<meta charset="UTF-8">(字符编码)或 CSS 链接。

Insight:解题洞察: On "find the HTML error" questions, the two most common planted bugs are: (1) a missing closing tag slash (e.g., <title> instead of </title>), and (2) a mismatched closing tag (closing the wrong element). Always check that each opening tag has a matching closing tag with a slash. Self-closing tags like <br> and <img> are the exceptions.在"找出 HTML 错误"题中,两种最常见的预设错误是:(1) 缺少结束标签斜杠(例如 <title> 代替 </title>),以及 (2) 不匹配的结束标签(关闭了错误的元素)。始终检查每个开始标签是否有带斜杠的匹配结束标签。<br><img> 等自闭合标签是例外。
Q11 MEDIUM 🇨🇦 ON 🇨🇦 BC ON Provincial-style安大略省考风格 §7 JSON and APIsJSON 与接口 · CSTA 3A-DA-12 [9 marks][9 分]

Weather API JSON response. Python parses and prints city, tomorrow forecast, and first alert.天气接口 JSON 响应。Python 解析并打印城市、明日预报和第一条警告。

Parts (a)-(e): See rationale below.第 (a)-(e) 部分:见下方详解。

Part (a) - Output第 (a) 部分 - 输出

Trace: city = "Vancouver", tomorrow = "sunny", first_alert = "fog warning" (index 0 of the alerts list). The f-string produces: [2]追踪:city = "Vancouver"tomorrow = "sunny"first_alert = "fog warning"(alerts 列表的索引 0)。f-string 产生:[2]

Vancouver: tomorrow will be sunny. Alert: fog warning

Part (b) - data["forecast"]["tomorrow"] step by step第 (b) 部分 - data["forecast"]["tomorrow"] 逐步解析

Step 1: data["forecast"] accesses the value associated with the key "forecast" in the top-level dictionary. That value is itself a dictionary: {"tomorrow": "sunny", "temp_high": 22.0}. [1]步骤 1:data["forecast"] 访问顶级字典中与键 "forecast" 关联的值。该值本身是一个字典:{"tomorrow": "sunny", "temp_high": 22.0}[1]

Step 2: ["tomorrow"] accesses the "tomorrow" key in that nested dictionary, returning the string "sunny". [1]步骤 2:["tomorrow"] 访问该嵌套字典中的 "tomorrow" 键,返回字符串 "sunny"[1]

Part (c) - Second alert第 (c) 部分 - 第二条警告

data["alerts"][1]

Python lists are 0-indexed: index 0 = "fog warning", index 1 = "wind advisory". [1]Python 列表从 0 开始索引:索引 0 = "fog warning",索引 1 = "wind advisory"[1]

Part (d) - JSON vs Python dict syntax differences第 (d) 部分 - JSON 与 Python 字典语法差异

Difference 1: JSON keys must be double-quoted strings. Python dictionary keys can be unquoted (if they are string literals, single quotes work too). Example: JSON requires "city": "Vancouver"; Python allows 'city': 'Vancouver' or city: 'Vancouver' (as a variable). [1]差异 1:JSON 键必须是双引号字符串。Python 字典键可以不带引号(如果是字符串字面量,单引号也可以)。示例:JSON 要求 "city": "Vancouver";Python 允许 'city': 'Vancouver'city: 'Vancouver'(作为变量)。[1]

Difference 2: JSON uses lowercase true/false/null for booleans and null; Python uses capitalised True/False/None. Example: JSON {"active": true} is invalid as Python dict syntax; Python is {"active": True}. [1]差异 2:JSON 对布尔值和 null 使用小写 true/false/null;Python 使用首字母大写的 True/False/None。示例:JSON {"active": true} 作为 Python 字典语法是无效的;Python 是 {"active": True}[1]

Part (e) - json.loads()第 (e) 部分 - json.loads()

json.loads(text) parses a JSON-formatted string and converts it into the equivalent Python data structure. [1] When the input is a JSON object (surrounded by {}), it returns a Python dict. When the input is a JSON array ([]), it returns a Python list. [1]json.loads(text) 解析 JSON 格式的字符串并将其转换为等效的 Python 数据结构。[1]当输入是 JSON 对象(被 {} 包围)时,返回 Python dict。当输入是 JSON 数组([])时,返回 Python list[1]

Insight:解题洞察: The name json.loads is a mnemonic: "loads" = "load string." Its counterpart json.dumps = "dump string" (converts Python back to a JSON string). For nested JSON, the access pattern chains index operations: outer key first, then inner key. Each [] descends one level into the nested structure.json.loads 的名称是助记符:"loads" = "load string"(加载字符串)。其对应的 json.dumps = "dump string"(转储字符串,将 Python 转换回 JSON 字符串)。对于嵌套 JSON,访问模式链接索引操作:先外层键,再内层键。每个 [] 向嵌套结构下降一层。
Q12 HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC AP CSP-feeder FRQAP CSP 衔接简答题 §6 + §7 HTML + JSON + data pipelineHTML + JSON + 数据管线 · CSTA 3A-DA-12 [8 marks][8 分]

Data pipeline: API returns JSON list of student scores; program generates HTML table.数据管线:接口以 JSON 列表返回学生成绩;程序生成 HTML 表格。

Parts (a)-(d): See rationale below.第 (a)-(d) 部分:见下方详解。

Part (a) - Type returned by json.loads第 (a) 部分 - json.loads 返回的类型

json.loads(api_response) returns a Python list. [1] You can tell because the JSON string starts with [ and ends with ]; square brackets denote a JSON array, which maps to a Python list. Each element of the array is a JSON object ({...}), which maps to a Python dict. [1]json.loads(api_response) 返回 Python list[1]可以从 JSON 字符串以 [ 开始、以 ] 结束判断,方括号表示 JSON 数组,映射到 Python 列表。数组的每个元素是 JSON 对象({...}),映射到 Python 字典。[1]

Part (b) - Complete HTML table output第 (b) 部分 - 完整 HTML 表格输出

The loop iterates over three student dicts: Alice/92, Bob/78, Carol/95. [1] for header row; [1] for first two data rows; [1] for Carol row and closing tag.循环遍历三个学生字典:Alice/92、Bob/78、Carol/95。[1]表头行;[1]前两个数据行;[1]Carol 行和结束标签。

<table>
  <tr><th>Name</th><th>Score</th></tr>
  <tr><td>Alice</td><td>92</td></tr>
  <tr><td>Bob</td><td>78</td></tr>
  <tr><td>Carol</td><td>95</td></tr>
</table>

Part (c) - Highlight high-scoring rows第 (c) 部分 - 高亮高分行

for s in students:
    if s['score'] >= 90:
        html += f"  <tr class='high'><td>{s['name']}</td><td>{s['score']}</td></tr>\n"
    else:
        html += f"  <tr><td>{s['name']}</td><td>{s['score']}</td></tr>\n"

Alice (92 >= 90) and Carol (95 >= 90) get class='high'; Bob (78 < 90) does not. [1] The if/else inside the loop selects the correct tag string for each student. [1]Alice(92 >= 90)和 Carol(95 >= 90)得到 class='high';Bob(78 < 90)不得到。[1]循环内的 if/else 为每个学生选择正确的标签字符串。[1]

Part (d) - Data-to-information transformation第 (d) 部分 - 数据到信息的转换

The raw JSON score values (e.g., 92, 78, 95) are data with no visual presentation or context; the program transforms them into a labelled, formatted HTML table that a user can read and understand, converting raw data into information. [1]原始 JSON 成绩值(如 92、78、95)是没有视觉呈现或上下文的数据;程序将其转换为用户可以阅读和理解的带标签的格式化 HTML 表格,将原始数据转换为信息。[1]

Insight:解题洞察: This question integrates all three web-data layers studied in this unit: JSON for data transmission, Python for processing, and HTML for presentation. Real-world web applications follow this exact pattern: a back-end API sends JSON; a front-end program renders it as HTML. The data-to-information pipeline (Section 1) is the conceptual thread connecting all seven sections of this unit.这道题整合了本单元学习的所有三个网络数据层:用于数据传输的 JSON、用于处理的 Python 和用于展示的 HTML。现实世界的网络应用遵循这个确切的模式:后端接口发送 JSON;前端程序将其渲染为 HTML。数据到信息的管线(第 1 节)是贯穿本单元全部七节的概念主线。