High School Computer Science

Data, Databases and the Web数据、数据库与网络

Every modern program stores, retrieves, and transmits data. This guide builds the complete picture: what data (data) and information (information) are and how they differ; how to read and write files (file) on disk; how comma-separated values (CSV) let programs share structured data; how relational databases (relational database) organise information into tables (table) linked by keys; how SQL queries (query) let you ask questions of a database with SELECT and WHERE; how HTML assembles a web page (web page); and how web APIs expose data in JSON format so programs can talk to each other over the internet. Code and SQL examples are shown in <pre><code> blocks with Chinese explanations alongside.每个现代程序都需要存储、检索和传输数据(data,数据)。本指南构建完整图景:数据(data,数据)与信息(information,信息)是什么、有何区别;如何从磁盘读写文件(file,文件);逗号分隔值(CSV)如何让程序共享结构化数据;关系数据库(relational database,关系数据库)如何将信息组织成通过键连接的表(table,表);SQL 查询(query,查询)如何通过 SELECT 和 WHERE 向数据库提问;HTML 如何组合网页(web page,网页);以及网络接口(API,接口)如何以 JSON 格式暴露数据,使程序能通过互联网相互通信。

7 sections7 节内容 US CSTA · AP CSP · ON · BC · ABUS CSTA · AP CSP · ON · BC · AB Python + SQL + HTML code examplesPython + SQL + HTML 代码示例

Data vs Information数据与信息

Learning objectives学习目标
  • Tell data from information by naming the context (label, unit, comparison) that gives a value meaning.
  • Name the Python data types int, float, str and bool, and predict how each behaves in +.
  • Turn a list of raw readings into information (an average, a count, the values above average) and describe the pattern it shows.
  • 通过指出赋予数值含义的上下文(标签、单位、比较)来区分数据与信息。
  • 说出 Python 的数据类型 int、float、str 和 bool,并预测它们在 + 下的行为。
  • 把一组原始读数转化为信息(平均值、个数、高于平均的值),并描述其中的规律。
Two definitions to lock in first.先锁定两个定义。
  • Data数据: raw, unprocessed facts and symbols. Examples: 98.6, "Alice", true, a pixel value. Data has no inherent meaning on its own.:原始、未经处理的事实和符号。例如:98.6、"Alice"、true、一个像素值。数据本身没有固有含义。
  • Information信息: data that has been processed, organised, or interpreted so it carries meaning. Example: "Alice's body temperature is 98.6°F, which is normal." Context turns data into information.:经过处理、组织或解释后具有含义的数据。例如:"Alice 的体温是 98.6°F,属于正常。"上下文将数据转变为信息。
  • Data types数据类型: integer, float, string, Boolean, list. Every value stored in a program belongs to a type. CSTA 3A-DA-10: "Evaluate the tradeoffs in how data elements are organized and where data is stored.":整数、浮点数、字符串、布尔值、列表。程序中存储的每个值都属于一种类型。CSTA 3A-DA-10:"评估数据元素的组织方式和存储位置的权衡。"
The AP CSP angle: Big Idea 2 (DAT) opens with "Data are central to computing innovations because they communicate initial conditions to programs and represent new knowledge." (AP CSP CED, verbatim). The whole Big Idea is built on the data → information pipeline this section introduces.AP CSP 视角:大概念 2(DAT)以"数据是计算创新的核心,因为它们向程序传递初始条件并代表新知识"开篇(AP CSP CED 原文)。整个大概念建立在本节介绍的数据 → 信息管线之上。
Worked Example 1: From sensor readings to a weather report例题 1:从传感器读数到天气报告

A weather station collects three sensor readings every minute: temperature, humidity, pressure. Show the data → information transformation.气象站每分钟采集三个传感器读数:温度、湿度、气压。展示数据 → 信息转换过程。

Raw data (numbers, no meaning without context).原始数据(数字,脱离上下文没有含义)。

22.4, 65, 1013.2
22.6, 64, 1013.0
22.9, 63, 1012.7

The three columns are temperature (°C), humidity (%), and pressure (hPa), but without column headers these numbers carry no meaning.三列分别是温度(°C)、湿度(%)、气压(hPa),但如果没有列标题,这些数字毫无意义。

Processing step: label, aggregate, interpret.处理步骤:标注、聚合、解释。

# Python: compute average temperature from a list of readings
readings = [22.4, 22.6, 22.9]
avg_temp = sum(readings) / len(readings)
print(f"Average temperature: {avg_temp:.1f} °C")
# Output: Average temperature: 22.6 °C

sum(readings) adds all values; len(readings) returns the list length; f"..." is a formatted string literal (f-string).sum(readings) 求和,len(readings) 取列表长度,f"..." 是格式化字符串。

Information.信息。 "Average temperature over the last 3 minutes: 22.6 °C. Trend: rising. Humidity dropping. Pressure falling slowly, so rain is possible within 6 hours." The same raw numbers now carry actionable meaning. CSTA 3A-DA-12: "Create computational models that represent the relationships among different elements of data collected from a phenomenon or process.""过去 3 分钟平均温度:22.6 °C。趋势:上升。湿度下降。气压缓慢下降,6 小时内可能有雨。"同样的原始数字现在具有了可行动的含义。CSTA 3A-DA-12:"创建计算模型,表示从现象或过程中收集的数据的不同元素之间的关系。"

Worked Example 2: Data types and a first summary例题 2:数据类型与初步汇总

Python stores every value with a type. (a) Predict the type of 17, 17.0, "17" and True, and what 17 + 17 and "17" + "17" give. (b) Four test results are stored as [87, 92, 74, 95]. Turn this data into information: find the class average and the scores above it.Python 为每个值存储一个类型。(a) 预测 17、17.0、"17" 和 True 的类型,以及 17 + 17 和 "17" + "17" 的结果。(b) 四个测验成绩存为 [87, 92, 74, 95]。把这些数据转化为信息:求班级平均分以及高于平均分的成绩。

(a) Types. The type decides what an operator does, so check it before you predict.(a) 类型。类型决定运算符的行为,预测前先确认类型。

values = [17, 17.0, "17", True]
for v in values:
    print(repr(v), type(v).__name__)
print(17 + 17)
print("17" + "17")

# Output:
# 17 int
# 17.0 float
# '17' str
# True bool
# 34
# 1717

17 is an int, 17.0 a float, "17" a str (the quotes make it text) and True a bool. + adds two numbers (34) but joins two strings ("1717"): the same symbols are data of different types, so they behave differently.17 是 int,17.0 是 float,"17" 是 str(引号表示文本),True 是 bool。+ 对两个数字做加法(34),对两个字符串做拼接("1717"):相同的符号,类型不同的数据,行为也不同。

(b) From data to information. The four numbers alone are data. Computing a summary and comparing each value with it adds meaning.(b) 从数据到信息。这四个数字本身只是数据。计算一个汇总值并把每个值与它比较,就增加了含义。

scores = [87, 92, 74, 95]
average = sum(scores) / len(scores)
above = [s for s in scores if s > average]
print(f"Class average: {average}")
print(f"Above average: {above}")

# Output:
# Class average: 87.0
# Above average: [92, 95]

Information: "The class average on the test is 87.0, and two of the four students (92 and 95) scored above it." The sum is 87 + 92 + 74 + 95 = 348, and 348 / 4 = 87.0. The pattern is that the two highest scores are the only ones above the average, which a bare list does not tell you. Note that / always gives a float, so the average prints as 87.0, not 87.信息:"这次测验的班级平均分是 87.0,四名学生中有两人(92 和 95)高于平均分。"总和为 87 + 92 + 74 + 95 = 348,348 / 4 = 87.0。规律是只有最高的两个成绩高于平均分,这是单纯的列表看不出来的。注意 / 总是得到 float,所以平均分打印为 87.0,而不是 87。

A spreadsheet contains the values 87, 92, 74, 95 with no labels. Which best describes these values?一张电子表格包含值 87, 92, 74, 95,没有标签。哪个最能描述这些值?
§1 · Q1
Information, because they are numbers信息,因为它们是数字
Information, because a computer can read them信息,因为计算机可以读取它们
Data, because they have no context or meaning数据,因为它们没有上下文或含义
Neither data nor information既不是数据也不是信息
Without labels, we do not know if these are test scores, temperatures, or IDs. Raw values with no context are data, not information. Only after labelling and interpreting (e.g., "these are exam scores; average = 87") do they become information.没有标签,我们不知道这些是考试成绩、温度还是 ID。没有上下文的原始值是数据,而非信息。只有在标注和解释后(如"这些是考试成绩;平均分 = 87"),它们才成为信息。
Being a number or being computer-readable does not make something information. Information requires context and meaning. Raw unlabelled values are data.是数字或可被计算机读取并不使某物成为信息。信息需要上下文和含义。未标注的原始值是数据。
CSTA standard 3A-DA-10 says "Evaluate the tradeoffs in how data elements are organized and where data is stored." Which choice is an example of such a tradeoff?CSTA 标准 3A-DA-10 说"评估数据元素组织方式和数据存储位置的权衡"。哪个选项是这种权衡的例子?
§1 · Q2
Choosing between Python and Java在 Python 和 Java 之间选择
Deciding whether to use a loop or recursion决定使用循环还是递归
Selecting a font for a report为报告选择字体
Storing student records in a flat CSV vs a relational database: CSV is simpler but harder to query across tables将学生记录存储为平面 CSV 与关系数据库:CSV 更简单但跨表查询更难
3A-DA-10 is about data organisation and storage decisions. Choosing between a flat file (CSV) and a relational database is a classic data-storage tradeoff: CSV is simple and portable but lacks relational querying power; a database is complex to set up but powerful to query.3A-DA-10 关于数据组织和存储决策。在平面文件(CSV)和关系数据库之间选择是经典的数据存储权衡:CSV 简单且可移植,但缺乏关系查询能力;数据库设置复杂,但查询功能强大。
Language choice, loop vs recursion, and fonts are not data organisation tradeoffs. The tradeoff CSTA 3A-DA-10 asks about is how and where to store data, for example CSV vs database.语言选择、循环与递归、字体都不是数据组织权衡。CSTA 3A-DA-10 问的权衡是如何以及在哪里存储数据,例如 CSV 与数据库。
Exam tip考试提示

When a question asks whether something is data or information, name the context that was added (a label, a unit, a comparison with an average) and say what it now means. Saying only "it has been processed" is an incomplete answer. A common error is calling every number information; an unlabelled number is data.

当题目问某物是数据还是信息时,要指出所添加的上下文(标签、单位、与平均值的比较)并说明它现在表示什么。只说“它被处理过”是不完整的答案。常见错误是把所有数字都叫作信息;没有标签的数字是数据。

Check your understanding自我检测
Is the value 98.6 data or information? Is the sentence "Alice's body temperature is 98.6 °F, which is normal" data or information?值 98.6 是数据还是信息?句子“Alice 的体温是 98.6 °F,属于正常”是数据还是信息?

98.6 alone is data: it has no label or unit. The sentence is information because the label (body temperature), the unit (°F) and an interpretation (normal) give it meaning.

单独的 98.6 是数据:它没有标签或单位。这个句子是信息,因为标签(体温)、单位(°F)和解释(正常)赋予了它含义。

Predict the output of print("17" + "17") and print(17 + 17), and explain the difference.预测 print("17" + "17") 和 print(17 + 17) 的输出,并解释区别。

The first prints 1717 (two str values are joined); the second prints 34 (two int values are added). The operator + depends on the data type.

第一个输出 1717(两个 str 被拼接);第二个输出 34(两个 int 相加)。运算符 + 的行为取决于数据类型。

For scores = [60, 70, 80, 90], what do average and [s for s in scores if s > average] give in the code of Worked Example 2?对于 scores = [60, 70, 80, 90],在例题 2 的代码中 average 和 [s for s in scores if s > average] 分别是什么?

The sum is 300 and the length is 4, so average is 75.0 (a float). The comprehension keeps the scores above 75.0, giving [80, 90].

总和为 300,长度为 4,所以 average 是 75.0(float)。列表推导式保留高于 75.0 的成绩,得到 [80, 90]。


File Input/Output (Reading and Writing Files)文件输入/输出(读写文件)

Learning objectives学习目标
  • Open a text file with mode "r", "w" or "a" and state what each does to existing content.
  • Read lines from a file, convert them with int(), and write results back with f.write().
  • Use a with block so the file is closed automatically, and predict a file's contents after a write and an append.
  • 用模式 "r"、"w" 或 "a" 打开文本文件,并说明每种模式对已有内容的影响。
  • 从文件读取行,用 int() 转换,并用 f.write() 把结果写回。
  • 使用 with 块自动关闭文件,并预测写入和追加之后文件的内容。
Three file operations to memorise.需要记住的三个文件操作。
  • Open打开: connect a program to a file on disk. Modes: "r" read, "w" write (overwrites), "a" append. CSE2130 outcome 1.4.2: "opening an existing file.":将程序连接到磁盘上的文件。模式:"r" 读取,"w" 写入(覆盖),"a" 追加。CSE2130 结果 1.4.2:"打开现有文件。"
  • Read / Write读取 / 写入: transfer data between the program and the file. Read brings data in; write sends data out. CSE2130 outcomes 1.4.5 "importing data from a file" and 1.4.4 "exporting data to a file.":在程序和文件之间传输数据。读取将数据带入;写入将数据送出。CSE2130 结果 1.4.5"从文件导入数据"和 1.4.4"将数据导出到文件"。
  • Close关闭: flush and disconnect. In Python, use with open(...) as f:, and the file closes automatically when the block exits. Always close files to avoid data loss.:刷新并断开连接。在 Python 中,使用 with open(...) as f:,代码块退出时文件自动关闭。始终关闭文件以避免数据丢失。
Ontario ICS4U A3.1 (verbatim): "demonstrate the ability to read from, and write to, an external file (e.g., text file, binary file, database, XML file) from within a computer program."安大略 ICS4U A3.1(原文):"展示从计算机程序内部读写外部文件(如文本文件、二进制文件、数据库、XML 文件)的能力。"
Worked Example 3: Reading a text file and writing a summary例题 3:读取文本文件并写入摘要

File scores.txt contains one integer per line. Read all scores, compute the average, and write the result to summary.txt.文件 scores.txt 每行包含一个整数。读取所有成绩,计算平均值,并将结果写入 summary.txt。

scores.txt (sample content).scores.txt(示例内容)。

87
92
74
95
88

Python: read, process, write.Python:读取、处理、写入。

# Read all scores from file
with open("scores.txt", "r") as f:
    scores = [int(line.strip()) for line in f]

# Process: compute average
average = sum(scores) / len(scores)

# Write summary to a new file
with open("summary.txt", "w") as f:
    f.write(f"Count: {len(scores)}\n")
    f.write(f"Average: {average:.1f}\n")

print("Done. summary.txt written.")

open("scores.txt", "r") opens the file in read-only mode; line.strip() removes the trailing newline; int(...) converts the string to an integer; open("summary.txt", "w") creates or overwrites the file in write mode; f.write(...) writes content; \n is the newline character.open("scores.txt", "r") 以只读模式("r",read)打开文件;line.strip() 去除换行符;int(...) 将字符串转为整数;open("summary.txt", "w") 以写入模式("w",write)创建/覆盖文件;f.write(...) 写入内容;\n 是换行符。

Output in summary.txt.summary.txt 中的输出。

Count: 5
Average: 87.2
Worked Example 4: Appending to a file and the missing-newline trap例题 4:向文件追加数据与缺少换行符的陷阱

The file scores.txt from Worked Example 3 holds 87, 92, 74, 95 and 88, one per line. A new score, 91, must be added without erasing the old ones. Add it, read the file back, and report the count, the last score and the new average. Then show what goes wrong if the old last line has no newline.例题 3 中的文件 scores.txt 每行一个数,依次为 87、92、74、95、88。需要在不删除旧成绩的前提下加入新成绩 91。添加它,重新读取文件,并报告个数、最后一个成绩和新的平均分。再说明如果旧的最后一行没有换行符会出什么问题。

Step 1: append, then read. Mode "a" positions the write cursor at the end, so the five old lines stay. The first block recreates the file so that it runs on its own.第 1 步:追加,再读取。模式 "a" 把写入位置放在末尾,所以原有的五行保留。第一段代码先重建文件,使其可以独立运行。

# scores.txt holds 87, 92, 74, 95, 88 (one per line, each line ends with a newline)
with open("scores.txt", "w") as f:
    f.write("87\n92\n74\n95\n88\n")

with open("scores.txt", "a") as f:       # append: keep the old lines
    f.write("91\n")

with open("scores.txt", "r") as f:
    scores = [int(line.strip()) for line in f]

print(len(scores), scores[-1], round(sum(scores) / len(scores), 1))

# Output:
# 6 91 87.8

There are now 6 scores, the last one is 91, and the average is (87 + 92 + 74 + 95 + 88 + 91) / 6 = 527 / 6 = 87.83..., which round(..., 1) shows as 87.8. Had the append step used "w" instead, the five old lines would have been erased first, leaving only 91.现在有 6 个成绩,最后一个是 91,平均分为 (87 + 92 + 74 + 95 + 88 + 91) / 6 = 527 / 6 = 87.83...,round(..., 1) 显示为 87.8。如果追加这一步改用 "w",会先清空五行旧内容,只剩 91。

Step 2: the missing-newline trap. Append mode adds text exactly where the file ends. If the last line has no \n, the new text joins onto it.第 2 步:缺少换行符的陷阱。追加模式把文本恰好加在文件末尾。如果最后一行没有 \n,新文本会接在它后面。

with open("bad.txt", "w") as f:
    f.write("87\n88")                   # no newline after 88

with open("bad.txt", "a") as f:
    f.write("91\n")

with open("bad.txt", "r") as f:
    print(repr(f.read()))

# Output:
# '87\n8891\n'

The file now holds 87 and 8891: the score 88 and the new score 91 have merged into one wrong value. The fix is to write "\n" after every record (as in the first block), so the next append starts on a fresh line.文件现在包含 87 和 8891:成绩 88 与新成绩 91 合并成了一个错误的值。解决办法是在每条记录后写入 "\n"(如第一段代码),这样下一次追加就从新的一行开始。

In Python, which mode string opens a file for appending (adding to the end without erasing existing content)?在 Python 中,哪个模式字符串以追加方式打开文件(在末尾添加内容而不删除现有内容)?
§2 · Q1
"r"
"a"
"w"
"x"
"a" is append mode: it opens the file and positions the write cursor at the end, so new data is added after existing content. "r" = read only, "w" = write (overwrites everything), "x" = create new file (fails if file exists)."a" 是追加模式:打开文件并将写入游标定位在末尾,因此新数据添加到现有内容之后。"r" = 只读,"w" = 写入(覆盖所有内容),"x" = 创建新文件(文件已存在则失败)。
File modes: "r" read, "w" write/overwrite, "a" append, "x" exclusive create. Appending means adding to the end without erasing; that is "a".文件模式:"r" 读取,"w" 写入/覆盖,"a" 追加,"x" 独占创建。追加意味着在末尾添加而不删除,那就是 "a"。
Why does Python's with open(...) as f: pattern eliminate the need to call f.close()?为什么 Python 的 with open(...) as f: 模式不需要调用 f.close()?
§2 · Q2
The with block automatically closes the file when the block exits, even if an error occurswith 块在代码块退出时自动关闭文件,即使发生错误也是如此
Python never needs files to be closedPython 从不需要关闭文件
The as f clause closes the file when f is reassignedas f 子句在 f 被重新赋值时关闭文件
Only write-mode files need to be closed只有写入模式的文件需要关闭
The with statement is a context manager. When execution leaves the with block (normally or via an exception), Python calls the file's __exit__ method, which flushes and closes the file. This guarantees no data is lost even if an error occurs mid-write.with 语句是一个上下文管理器。当执行离开 with 块时(正常退出或通过异常),Python 调用文件的 __exit__ 方法,该方法刷新并关闭文件。这保证即使写入过程中发生错误,数据也不会丢失。
Files should always be closed to flush buffers and release the OS file handle. The with block handles this automatically via Python's context manager protocol.文件应始终关闭以刷新缓冲区并释放操作系统文件句柄。with 块通过 Python 的上下文管理器协议自动处理这一点。
Exam tip考试提示

Name the mode and say what it does to the existing content: "w" overwrites, "a" appends, "r" only reads. Command words such as "state" and "explain" want that consequence, not just the letter. Common errors: using "w" when the question says "add", forgetting the \n at the end of each written line, and using the file after the with block has closed it.

写出模式并说明它对已有内容的影响:"w" 覆盖,"a" 追加,"r" 只读。“说明”“解释”等指令词需要的是这个结果,而不只是字母。常见错误:题目说“添加”时却用 "w",忘记在每行写入的末尾加 \n,以及在 with 块关闭文件之后继续使用文件。

Check your understanding自我检测
notes.txt holds the lines a and b. A program opens it with "w" and writes the line c. What does the file hold afterwards?notes.txt 中有 a、b 两行。程序用 "w" 打开它并写入一行 c。之后文件里是什么?

Only the line c. Mode "w" erases the old content as soon as the file is opened.

只有 c 这一行。模式 "w" 在打开文件时就清除了旧内容。

The same file (now holding only c) is opened with "a" and the line d is written. What does it hold, and which mode would you use to read it back?同一个文件(现在只有 c)用 "a" 打开并写入一行 d。文件里是什么?读取时用哪种模式?

It holds the lines c and d ('c\nd\n'), because append keeps the old content and adds at the end. To read it back use "r".

文件里是 c 和 d 两行('c\nd\n'),因为追加会保留旧内容并添加到末尾。读取时用 "r"。

A loop for line in f: print(line) prints a blank line between the records. Why, and what are two fixes?循环 for line in f: print(line) 在每条记录之间多打印了一个空行。为什么?有哪两种修复方法?

Each line still ends with \n, and print adds another newline. Fix it with print(line.strip()) or print(line, end="").

每个 line 末尾仍带着 \n,而 print 又添加了一个换行。用 print(line.strip()) 或 print(line, end="") 修复。


CSV and Structured DataCSV 与结构化数据

Learning objectives学习目标
  • Describe a CSV file in terms of header row, record, field and delimiter, and say why it is an organised, portable format.
  • Read a CSV with csv.DictReader, convert string fields to numbers, and group records to find a pattern such as an average per grade.
  • Write a CSV with csv.writer and explain why splitting a line on commas by hand fails when a field contains a comma.
  • 用标题行、记录、字段和分隔符描述 CSV 文件,并说明它为什么是有组织且便于移植的格式。
  • 用 csv.DictReader 读取 CSV,把字符串字段转换为数字,并对记录分组以发现规律,例如每个年级的平均分。
  • 用 csv.writer 写 CSV,并解释当字段内含逗号时为什么手动按逗号切分会出错。
CSV in three facts.CSV 的三个要点。
  • CSV = Comma-Separated ValuesCSV = 逗号分隔值: a plain-text format where each line is a record and fields within a line are separated by commas. The first line is usually a header row naming each column.:一种纯文本格式,每行是一条记录,行内字段用逗号分隔。第一行通常是命名每列的标题行。
  • Universal exchange format通用交换格式: spreadsheets, databases, and programs all export/import CSV. It is the most common format for sharing tabular data between systems. CSTA 3A-DA-11 says to "create interactive data visualisations"; CSV is how you get the data in.:电子表格、数据库和程序都可以导出/导入 CSV。它是系统间共享表格数据最常见的格式。CSTA 3A-DA-11 要求"创建互动数据可视化";CSV 就是数据的来源方式。
  • Python's csv modulePython 的 csv 模块: csv.reader parses each row into a list; csv.DictReader maps each row to a dictionary keyed by column name. Always prefer DictReader for named columns.:csv.reader 将每行解析为列表;csv.DictReader 将每行映射为以列名为键的字典。对于有名列,始终优先使用 DictReader。
Worked Example 5: Reading a CSV of student records例题 5:读取学生记录的 CSV

File students.csv stores name, grade, and score. Read it and print students who scored above 85.文件 students.csv 存储姓名、年级和成绩。读取它并打印成绩高于 85 的学生。

students.csv content.students.csv 内容。

name,grade,score
Alice,11,92
Bob,11,78
Carol,12,95
David,12,82
Eve,11,88

Python: filter rows where score > 85.Python:过滤成绩 > 85 的行。

import csv

with open("students.csv", "r") as f:
    reader = csv.DictReader(f)
    for row in reader:
        if int(row["score"]) > 85:
            print(row["name"], row["score"])

# Output:
# Alice 92
# Carol 95
# Eve 88

import csv loads the built-in csv module; csv.DictReader(f) reads each row as a dictionary (e.g. {"name": "Alice", "grade": "11", "score": "92"}); int(row["score"]) converts the string to an integer before comparing; row["name"] accesses a field by column name.import csv 导入内置 csv 模块;csv.DictReader(f) 将每行读为字典({"name": "Alice", "grade": "11", "score": "92"});int(row["score"]) 将字符串转为整数后比较;row["name"] 通过列名访问字段。

Worked Example 6: Averages per grade, and a field that contains a comma例题 6:按年级求平均分,以及含逗号的字段

Using students.csv from Worked Example 5, find how many students are in each grade and each grade's average score. Then write a new record whose name contains a comma, and show why split(",") cannot read it back.使用例题 5 的 students.csv,求每个年级有多少名学生以及每个年级的平均成绩。然后写入一条姓名含逗号的新记录,并说明为什么 split(",") 无法正确读回它。

Step 1: group the records. A dictionary maps each grade to a list of its scores. setdefault creates the empty list the first time a grade appears. The first lines recreate the file so the block runs by itself.第 1 步:对记录分组。用字典把每个年级映射到该年级的成绩列表。年级第一次出现时,setdefault 会创建空列表。开头几行重建文件,使这段代码可以独立运行。

import csv

with open("students.csv", "w", newline="") as f:
    f.write("name,grade,score\nAlice,11,92\nBob,11,78\nCarol,12,95\nDavid,12,82\nEve,11,88\n")

totals = {}
with open("students.csv", "r", newline="") as f:
    for row in csv.DictReader(f):
        totals.setdefault(row["grade"], []).append(int(row["score"]))

for grade in sorted(totals):
    scores = totals[grade]
    print(grade, len(scores), sum(scores) / len(scores))

# Output:
# 11 3 86.0
# 12 2 88.5

Grade 11 holds Alice (92), Bob (78) and Eve (88): (92 + 78 + 88) / 3 = 258 / 3 = 86.0. Grade 12 holds Carol (95) and David (82): (95 + 82) / 2 = 88.5. The pattern is that the smaller grade 12 group has the higher average. Each key is a string such as "11", because every CSV field is read as text; the scores were converted with int() before adding.11 年级有 Alice (92)、Bob (78) 和 Eve (88):(92 + 78 + 88) / 3 = 258 / 3 = 86.0。12 年级有 Carol (95) 和 David (82):(95 + 82) / 2 = 88.5。规律是人数较少的 12 年级平均分更高。每个键都是 "11" 这样的字符串,因为 CSV 的每个字段都以文本读取;成绩在相加前已用 int() 转换。

Step 2: a name with a comma. csv.writer wraps such a field in quotes. Splitting the line by hand ignores the quotes.第 2 步:含逗号的姓名。csv.writer 会用引号把这样的字段括起来。手动切分一行时会忽略这些引号。

import csv

with open("new.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerow(["name", "grade", "score"])
    writer.writerow(["Lee, Amy", 11, 90])

with open("new.csv", "r", newline="") as f:
    text = f.read()
line = text.splitlines()[1]
print(line)
print(line.split(","))

# Output:
# "Lee, Amy",11,90
# ['"Lee', ' Amy"', '11', '90']

The file line is "Lee, Amy",11,90: three fields, with the name quoted so its comma is data and not a delimiter. split(",") cuts at every comma and returns four pieces, with the quotes still attached. csv.reader and csv.DictReader understand the quotes and return the three fields Lee, Amy, 11 and 90. Always use the csv module for reading and writing CSV.文件中的这一行是 "Lee, Amy",11,90:三个字段,姓名被加了引号,所以其中的逗号是数据而不是分隔符。split(",") 在每个逗号处切开,得到四段,引号还连在上面。csv.reader 和 csv.DictReader 能识别引号,返回三个字段 Lee, Amy、11 和 90。读写 CSV 时始终使用 csv 模块。

In a CSV file, the first row is name,grade,score. What is this row called?在 CSV 文件中,第一行是 name,grade,score。这一行叫什么?
§3 · Q1
A record记录
A field字段
A header row标题行
A delimiter分隔符
The first row of a CSV is the header row: it names each column. Every subsequent row is a record (one row of data). Each item within a row is a field. The comma is the delimiter (separator character).CSV 的第一行是标题行,它命名每列。之后的每行是一条记录(一行数据)。行内每项是一个字段。逗号是分隔符(分隔字符)。
Header row = first row naming columns. Record = a subsequent data row. Field = one value within a row. Delimiter = the comma separator character.标题行 = 命名列的第一行。记录 = 后续数据行。字段 = 行内一个值。分隔符 = 逗号分隔字符。
A program reads a CSV where all values are strings. To compare the score field to 85 numerically, what must you do first?程序读取一个 CSV,所有值都是字符串。要将 score 字段与 85 进行数值比较,必须先做什么?
§3 · Q2
Nothing: Python compares strings and integers automatically什么都不用做:Python 自动比较字符串和整数
Convert the string to an integer using int(row["score"])使用 int(row["score"]) 将字符串转换为整数
Convert 85 to a string using str(85)使用 str(85) 将 85 转换为字符串
Use double equals: row["score"] == 85使用双等号:row["score"] == 85
CSV values are always read as strings. Comparing "92" > 85 would raise a TypeError in Python 3 (or give wrong results in Python 2). You must first convert: int(row["score"]) > 85. This is the most common bug when processing CSV data.CSV 值始终作为字符串读取。在 Python 3 中,比较 "92" > 85 会引发 TypeError(在 Python 2 中会给出错误结果)。必须先转换:int(row["score"]) > 85。这是处理 CSV 数据时最常见的错误。
Python 3 raises a TypeError if you compare a string to an integer with >. CSV fields are always strings, so convert them first with int() or float() before numeric comparison.Python 3 中用 > 比较字符串和整数会引发 TypeError。CSV 字段始终是字符串,所以在数值比较之前先用 int() 或 float() 转换。
Exam tip考试提示

Use the right words for the parts of a CSV: the first row is the header row, each later row is a record, each value is a field, and the comma is the delimiter. When you compare or add a field, show the int() or float() conversion; without it the value is a string. Common errors: calling the header a record, and splitting a line on commas by hand.

用对 CSV 各部分的术语:第一行是标题行,之后每一行是一条记录,每个值是一个字段,逗号是分隔符。比较或相加某个字段时,要写出 int() 或 float() 转换;没有转换,值仍是字符串。常见错误:把标题行叫作记录,以及手动按逗号切分一行。

Check your understanding自我检测
A line in a CSV with the header name,grade,score is Lee, Amy,11,90 (no quotes). How many fields does split(",") find, and what is wrong with the file?一个 CSV 的标题为 name,grade,score,其中一行是 Lee, Amy,11,90(没有引号)。split(",") 找到几个字段?这个文件有什么问题?

It finds four fields, but the header promises three. The name contains a comma, so the field should have been written in quotes, "Lee, Amy", which csv.writer does automatically.

找到四个字段,但标题只有三列。姓名里含逗号,所以该字段应该写成带引号的 "Lee, Amy",csv.writer 会自动这样做。

For row = {"name": "Alice", "score": "92"}, what do row["score"] * 2 and row["score"] + 5 do, and how do you get 97?对于 row = {"name": "Alice", "score": "92"},row["score"] * 2 和 row["score"] + 5 分别会怎样?如何得到 97?

row["score"] is the string "92", so * 2 repeats it to give "9292" and + 5 raises a TypeError (a str cannot be added to an int). int(row["score"]) + 5 gives 97.

row["score"] 是字符串 "92",所以 * 2 把它重复得到 "9292",而 + 5 会引发 TypeError(str 不能与 int 相加)。int(row["score"]) + 5 得到 97。

In Worked Example 6, which grade has the higher average, and why is it risky to rely on that pattern with only two students in grade 12?在例题 6 中,哪个年级的平均分更高?为什么只有两名 12 年级学生时依赖这个规律有风险?

Grade 12 (88.5 against 86.0). With only two students, one more score could change the average a lot, so the pattern is weak evidence.

12 年级更高(88.5 对 86.0)。只有两名学生时,多一个成绩就可能大幅改变平均分,所以这个规律的证据很弱。


Relational Databases and Tables关系数据库与表

Learning objectives学习目标
  • Identify the primary key and the foreign key in a pair of tables, and read which rows are linked by matching key values.
  • Explain how normalisation (storing each fact once) keeps data consistent, using an update example.
  • Describe what a database with foreign-key checking does when a row refers to a key that does not exist.
  • 在一对表中识别主键和外键,并通过匹配的键值读出哪些行相关联。
  • 用更新的例子解释规范化(每个事实只存储一次)如何保持数据一致。
  • 描述启用外键检查的数据库在某行引用不存在的键时会怎么做。
Four key terms for relational databases.关系数据库的四个关键术语。
  • Table表: a two-dimensional grid of data: rows (records) and columns (fields/attributes). Like a CSV, but stored in the database engine.:二维数据网格:行(记录)和列(字段/属性)。类似 CSV,但存储在数据库引擎中。
  • Primary key主键: a column (or set of columns) whose value uniquely identifies each row. Example: student_id in a Students table. No two rows may share the same primary key.:唯一标识每行的列(或列集合)。例如:Students 表中的 student_id。任何两行不得共享相同的主键。
  • Foreign key外键: a column in one table that references the primary key of another table. This is the "relational" part: it links two tables together. CSTA 3A-DA-10: "Evaluate the tradeoffs in how data elements are organized.":一个表中引用另一个表主键的列。这就是"关系"的部分:它将两个表连接在一起。CSTA 3A-DA-10:"评估数据元素组织方式的权衡。"
  • Normalisation规范化: organising data to reduce duplication. Instead of repeating a student's name in every grade record, store the name once in the Students table and reference it by ID.:组织数据以减少重复。与其在每条成绩记录中重复学生姓名,不如在 Students 表中存储一次姓名并通过 ID 引用。
ICS4C A2.2 (verbatim): "demonstrate the ability to read from, and write to, an external file (e.g., sequential file, database, XML file, relational database via SQL)." Note: this is the Ontario college stream (Grade 12 ICS4C), not the university stream (ICS4U).ICS4C A2.2(原文):"展示读写外部文件(如顺序文件、数据库、XML 文件、通过 SQL 的关系数据库)的能力。"注意:这是安大略学院流(12 年级 ICS4C),而非大学流(ICS4U)。
Worked Example 7: Two linked tables, Students and Scores例题 7:两个关联表(Students 与 Scores)

Design a relational database for student grades. One table stores students; another stores scores. Link them with a foreign key.为学生成绩设计一个关系数据库。一个表存储学生;另一个表存储成绩。用外键将它们连接。

Table 1: Students (primary key = student_id).表 1:Students(主键 = student_id)。

student_idnamegrade
1Alice11
2Bob11
3Carol12

Table 2: Scores (primary key = score_id; foreign key = student_id references Students).表 2:Scores(主键 = score_id;外键 = student_id 引用 Students)。

score_idstudent_idsubjectscore
11Math92
21CS88
32Math78
43CS95

Alice's name is stored once in Students. Her two score rows in Scores reference her by student_id = 1. If her name changes, we update it in one place only, which is the benefit of normalisation. Without a relational design, every score row would repeat her full name, and the copies could disagree after an edit.Alice 的姓名在 Students 中只存储一次。她在 Scores 中的两条成绩行通过 student_id = 1 引用她。如果她的姓名变了,只需在一个地方更新,这就是规范化的好处。没有关系设计,每条成绩行都要重复她的全名,修改后各份副本可能互相矛盾。

Students tableStudents 表 Scores tableScores 表 PKPK PKPK FKFK student_idstudent_id namename gradegrade 11 AliceAlice 1111 22 BobBob 1111 33 CarolCarol 1212 score_idscore_id student_idstudent_id subjectsubject scorescore 11 11 MathMath 9292 22 11 CSCS 8888 33 22 MathMath 7878 44 33 CSCS 9595 Alice (student_id 1) has two lines: two Scores rows.Alice(student_id 1)有两条线:两条 Scores 行。 FK values 1, 1, 2, 3 point to PK values 1, 2, 3.外键值 1、1、2、3 指向主键值 1、2、3。
Figure 1. The Students and Scores tables of Worked Example 7. Each line joins a foreign key value in Scores.student_id to the primary key it refers to in Students: Alice (1) is reached by score_id 1 and 2 (Math 92, CS 88), Bob (2) by score_id 3 (Math 78) and Carol (3) by score_id 4 (CS 95). Reading across a line gives the JOIN result.图 1. 例题 7 的 Students 表和 Scores 表。每条线把 Scores.student_id 中的外键值连到它在 Students 中引用的主键:Alice (1) 对应 score_id 1 和 2(Math 92、CS 88),Bob (2) 对应 score_id 3(Math 78),Carol (3) 对应 score_id 4(CS 95)。沿着线读取就得到 JOIN 的结果。
Worked Example 8: Updating one fact, and rejecting a row with no parent例题 8:更新一个事实,以及拒绝没有父记录的行

Alice (student_id 1) changes her name to Alice Wu. (a) How many rows must change if names are stored once in Students, and how many if every score row repeats the name? (b) What should happen if someone adds a Scores row for student_id 9, who does not exist? Check both with Python's sqlite3 module on the tables of Worked Example 7.Alice(student_id 1)把名字改为 Alice Wu。(a) 如果姓名只在 Students 中存储一次,需要改几行?如果每条成绩行都重复姓名,又需要改几行?(b) 如果有人为不存在的 student_id 9 添加一条 Scores 行,应该发生什么?用 Python 的 sqlite3 模块在例题 7 的表上检验这两点。

Predict first. Alice has two Scores rows (score_id 1 and 2). With the name stored once, one row changes. If each score row repeated the name, two rows would change, and an update that missed one of them would leave "Alice" and "Alice Wu" in the same table for the same student. For (b), a foreign key must match an existing primary key, so the database should refuse the row.先预测。Alice 有两条 Scores 行(score_id 1 和 2)。姓名只存一次时,只需改一行。如果每条成绩行都重复姓名,就要改两行,而且只要漏改其中一行,同一个学生就会在同一个表里同时出现“Alice”和“Alice Wu”。对于 (b),外键必须匹配已有的主键,所以数据库应拒绝这一行。

import sqlite3

db = sqlite3.connect(":memory:")
db.execute("PRAGMA foreign_keys = ON")
db.execute("CREATE TABLE Students (student_id INTEGER PRIMARY KEY, name TEXT, grade INTEGER)")
db.execute("CREATE TABLE Scores (score_id INTEGER PRIMARY KEY, student_id INTEGER REFERENCES Students(student_id), subject TEXT, score INTEGER)")
db.executemany("INSERT INTO Students VALUES (?, ?, ?)", [(1, "Alice", 11), (2, "Bob", 11), (3, "Carol", 12)])
db.executemany("INSERT INTO Scores VALUES (?, ?, ?, ?)", [(1, 1, "Math", 92), (2, 1, "CS", 88), (3, 2, "Math", 78), (4, 3, "CS", 95)])

changed = db.execute("UPDATE Students SET name = 'Alice Wu' WHERE student_id = 1").rowcount
print("Rows changed:", changed)

try:
    db.execute("INSERT INTO Scores VALUES (5, 9, 'Math', 70)")
except sqlite3.IntegrityError as error:
    print("Rejected:", error)
print(db.execute("SELECT COUNT(*) FROM Scores").fetchone()[0])

# Output:
# Rows changed: 1
# Rejected: FOREIGN KEY constraint failed
# 4

The update reports Rows changed: 1: one edit in Students, and the join in the next section still finds both of Alice's scores. The insert is rejected with FOREIGN KEY constraint failed because student_id 9 is not a primary key in Students, and the table still has 4 rows. SQLite checks foreign keys only after PRAGMA foreign_keys = ON is run; other database systems check them by default. A row whose foreign key points nowhere is called an orphan.更新报告 Rows changed: 1:只在 Students 中改了一处,下一节的连接查询仍能找到 Alice 的两条成绩。插入被拒绝,提示 FOREIGN KEY constraint failed,因为 student_id 9 不是 Students 中的主键,表中仍是 4 行。SQLite 只有在执行 PRAGMA foreign_keys = ON 之后才检查外键;其他数据库系统默认检查。外键指向不存在的行,这样的行称为孤儿行。

The tradeoff: a single flat table (like a CSV) is simpler to read, but it repeats facts and invites inconsistency; linked tables take more design but keep each fact in one place.权衡:单个平面表(如 CSV)更容易阅读,但会重复事实并容易出现不一致;关联表需要更多设计,但让每个事实只存在于一处。

In a relational database, what is the purpose of a primary key?在关系数据库中,主键的作用是什么?
§4 · Q1
To uniquely identify each row in a table唯一标识表中的每行
To store the most important data value存储最重要的数据值
To link two tables together将两个表连接在一起
To sort the rows alphabetically按字母顺序对行排序
A primary key uniquely identifies each row: no two rows can share the same value. It is not necessarily the most important data value (it is often just an auto-incremented ID). A foreign key (not primary key) is what links two tables.主键唯一标识每行:任何两行不能共享相同的值。它不一定是最重要的数据值(通常只是一个自动递增的 ID)。外键(不是主键)才是连接两个表的东西。
Primary key = unique identifier for each row. Foreign key = a column that references the primary key of another table (linking two tables). Sorting is done by ORDER BY in SQL, not by the primary key definition.主键 = 每行的唯一标识符。外键 = 引用另一个表主键的列(连接两个表)。排序由 SQL 中的 ORDER BY 完成,不是由主键定义决定的。
A Scores table has a column student_id that references the student_id column in the Students table. What is student_id called in the Scores table?Scores 表有一列 student_id,它引用 Students 表中的 student_id 列。student_id 在 Scores 表中叫什么?
§4 · Q2
Primary key主键
Index key索引键
Foreign key外键
Composite key复合键
A column in one table that references the primary key of another table is called a foreign key. It is what makes the database "relational": the Scores table is related to the Students table through this link.一个表中引用另一个表主键的列称为外键。这就是使数据库成为"关系型"的原因:Scores 表通过这个链接与 Students 表相关联。
Foreign key = a column that references another table's primary key. Primary key = the unique identifier of the current table's rows. An index key is a performance optimisation (not a referential constraint). A composite key is a primary key made of multiple columns.外键 = 引用另一个表主键的列。主键 = 当前表行的唯一标识符。索引键是性能优化(不是引用约束)。复合键是由多列组成的主键。
Exam tip考试提示

Define each key in terms of its own table: a primary key uniquely identifies the rows of the table it belongs to, and a foreign key is a column that holds values of another table's primary key. Use the tables in the question to point to the link (for example, Scores.student_id refers to Students.student_id). Common errors: swapping the two keys, and saying a foreign key must be unique (it can repeat, as Alice's student_id does).

按各自所在的表来定义每种键:主键唯一标识它所在表的行,外键是存放另一个表主键值的列。用题目中的表指出这个关联(例如 Scores.student_id 引用 Students.student_id)。常见错误:把两种键弄反,以及说外键必须唯一(它可以重复,Alice 的 student_id 就出现了两次)。

Check your understanding自我检测
In the Scores table (score_id, student_id, subject, score), which column is the primary key and which is the foreign key?在 Scores 表(score_id、student_id、subject、score)中,哪一列是主键,哪一列是外键?

score_id is the primary key (it identifies each score row). student_id is the foreign key (it refers to the primary key of Students).

score_id 是主键(标识每条成绩行)。student_id 是外键(引用 Students 的主键)。

Using Worked Example 7, how many Scores rows belong to Bob, and who owns the row with score_id 4?根据例题 7,有几条 Scores 行属于 Bob?score_id 为 4 的行属于谁?

Bob (student_id 2) has one row (score_id 3, Math 78). The row with score_id 4 has student_id 3, which is Carol (CS 95).

Bob(student_id 2)有一条行(score_id 3,Math 78)。score_id 为 4 的行 student_id 为 3,即 Carol(CS 95)。

A new row (5, 9, 'Math', 70) is added to Scores. What is wrong with it?向 Scores 添加了一行 (5, 9, 'Math', 70)。它有什么问题?

Its foreign key 9 matches no student_id in Students, so the row is an orphan. A database that checks foreign keys rejects it.

它的外键 9 与 Students 中任何 student_id 都不匹配,所以这行是孤儿行。检查外键的数据库会拒绝它。


SQL Basics: SELECT and WHERESQL 基础:SELECT 与 WHERE

Learning objectives学习目标
  • Write a SELECT statement with WHERE and ORDER BY and predict the rows it returns from a small table.
  • Combine two tables with JOIN ... ON a primary key and a foreign key, and group rows with GROUP BY, COUNT and AVG.
  • Explain how NULL behaves: it is skipped by COUNT(column) and AVG, never equals anything, and is found with IS NULL.
  • 编写带 WHERE 和 ORDER BY 的 SELECT 语句,并预测它从小表中返回的行。
  • 用主键和外键通过 JOIN ... ON 合并两个表,并用 GROUP BY、COUNT 和 AVG 对行分组。
  • 解释 NULL 的行为:COUNT(列) 和 AVG 会跳过它,它不等于任何值,需用 IS NULL 查找。
The four SQL keywords you need first.首先需要掌握的四个 SQL 关键字。
  • SELECT: choose which columns to return. SELECT * returns all columns; SELECT name, score returns only those two.:选择要返回的列。SELECT * 返回所有列;SELECT name, score 只返回那两列。
  • FROM: specify the table to query. Every SELECT needs a FROM.:指定要查询的表。每个 SELECT 都需要 FROM。
  • WHERE: filter rows. Only rows where the condition is true are returned. Operators: =, <, >, <=, >=, !=, LIKE, AND, OR.:过滤行。只返回条件为真的行。运算符:=、<、>、<=、>=、!=、LIKE、AND、OR。
  • ORDER BY: sort the results. ORDER BY score DESC sorts highest-first; ASC is lowest-first (the default).:对结果排序。ORDER BY score DESC 按从高到低排序;ASC 从低到高(默认)。
SQL is not case-sensitive for keywords, but convention capitalises them. SQL statements end with ;. ICS4C A2.2 names "relational database via SQL" explicitly. CSTA 3A-DA-10 says to "evaluate the tradeoffs in how data elements are organized and where data is stored"; SQL is the access layer on top of the organised storage.SQL 关键字不区分大小写,但约定大写。SQL 语句以 ; 结尾。ICS4C A2.2 明确点名"通过 SQL 的关系数据库"。CSTA 3A-DA-10 要求"评估数据元素组织方式和存储位置的权衡";SQL 是有组织存储之上的访问层。
Worked Example 9: Three SQL queries on the Students/Scores tables例题 9:对 Students/Scores 表的三个 SQL 查询

Using the two tables from §4, write SQL queries to answer common questions.使用 §4 中的两个表,编写 SQL 查询来回答常见问题。

Query 1: Get all students.查询 1:获取所有学生。

SELECT * FROM Students;

SELECT * selects all columns; FROM Students specifies the Students table. All three rows are returned.SELECT * 选择所有列,FROM Students 从 Students 表查询。返回所有三行。

Query 2: Get the student ID, subject and score where score > 85.查询 2:获取成绩 > 85 的学生 ID、科目和成绩。

SELECT student_id, subject, score
FROM Scores
WHERE score > 85
ORDER BY score DESC;

WHERE score > 85 filters rows to those with a score above 85; ORDER BY score DESC sorts the results from highest to lowest (DESC = descending).WHERE score > 85 过滤条件;ORDER BY score DESC 按成绩从高到低排序(DESC = descending,降序)。

Expected result (from the §4 data):预期结果(来自 §4 数据):

student_idsubjectscore
3CS95
1Math92
1CS88

Query 3: Count how many CS scores exist.查询 3:统计 CS 成绩的条数。

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

COUNT(*) counts the number of matching rows. Result: 2 (Carol and Alice each have one CS record).COUNT(*) 计算匹配行的数量。结果:2(Carol 和 Alice 各有一条 CS 记录)。

Worked Example 10: JOIN, GROUP BY and NULL例题 10:JOIN、GROUP BY 与 NULL

Use the Students and Scores tables of Worked Example 7. (a) List each score of 88 or more with the student's name, highest first. (b) For each subject, show how many scores there are and their average. (c) A fifth Scores row, (5, 2, 'Art', NULL), is added with no score yet. Show what COUNT, AVG and the conditions do with the NULL.使用例题 7 的 Students 和 Scores 表。(a) 列出所有 88 分及以上的成绩及学生姓名,分数高的在前。(b) 对每个科目,显示成绩条数及平均分。(c) 新增第五条 Scores 行 (5, 2, 'Art', NULL),尚无成绩。说明 COUNT、AVG 和条件如何处理 NULL。

(a) JOIN. The name lives in Students and the score in Scores, so the query joins them where the foreign key equals the primary key. Prefix a column with its table name when both tables could have it.(a) JOIN。姓名在 Students,成绩在 Scores,所以查询要在外键等于主键的地方把两表连接起来。当两个表都可能有同名列时,要在列名前加表名。

SELECT Students.name, Scores.subject, Scores.score
FROM Scores
JOIN Students ON Scores.student_id = Students.student_id
WHERE Scores.score >= 88
ORDER BY Scores.score DESC;
namesubjectscore
CarolCS95
AliceMath92
AliceCS88

Bob's 78 is filtered out by WHERE. Alice appears twice because she has two matching Scores rows: a join returns one result row per matching pair.Bob 的 78 被 WHERE 过滤掉了。Alice 出现两次,因为她有两条匹配的 Scores 行:连接对每一对匹配的行返回一行结果。

(b) GROUP BY. Rows with the same subject are collapsed into one result row, and the aggregate functions work on each group.(b) GROUP BY。科目相同的行被合并为一行结果,聚合函数对每个组分别计算。

SELECT subject, COUNT(*) AS n, AVG(score) AS avg_score
FROM Scores
GROUP BY subject
ORDER BY subject;
subjectnavg_score
CS291.5
Math285.0

CS has scores 88 and 95: (88 + 95) / 2 = 91.5. Math has 92 and 78: (92 + 78) / 2 = 85.0. The rows are in alphabetical order because of ORDER BY subject.CS 的成绩是 88 和 95:(88 + 95) / 2 = 91.5。Math 的成绩是 92 和 78:(92 + 78) / 2 = 85.0。因为有 ORDER BY subject,结果按字母顺序排列。

(c) NULL. NULL means "no value". It is not 0 and not an empty string. Run these on the table after the fifth row is added:(c) NULL。NULL 表示“没有值”。它不是 0,也不是空字符串。在加入第五行之后,对该表执行下面的查询:

QueryResult
SELECT COUNT(*), COUNT(score), AVG(score) FROM Scores;5, 4, 88.25
SELECT subject, score FROM Scores WHERE score > 85 ORDER BY score DESC;CS 95, Math 92, CS 88
SELECT * FROM Scores WHERE score = NULL;no rows
SELECT * FROM Scores WHERE score IS NULL;5, 2, Art, NULL

COUNT(*) counts every row (5) but COUNT(score) counts only rows where score is not NULL (4). AVG(score) skips the NULL: (92 + 88 + 78 + 95) / 4 = 353 / 4 = 88.25, not 353 / 5. A comparison with NULL is never true, so score > 85 skips the Art row and score = NULL returns nothing; IS NULL is the test that finds it.COUNT(*) 统计所有行(5),而 COUNT(score) 只统计 score 不为 NULL 的行(4)。AVG(score) 会跳过 NULL:(92 + 88 + 78 + 95) / 4 = 353 / 4 = 88.25,而不是 353 / 5。与 NULL 的比较永远不为真,所以 score > 85 会跳过 Art 这一行,score = NULL 什么也不返回;找到它要用 IS NULL。

Which SQL query returns only the name column from the Students table where the grade is 11?哪个 SQL 查询从 Students 表中只返回 grade 为 11 的 name 列?
§5 · Q1
SELECT * FROM Students;
SELECT Students WHERE grade = 11;
SELECT name WHERE grade = 11;
SELECT name FROM Students WHERE grade = 11;
A complete SELECT needs: SELECT <columns> FROM <table> WHERE <condition>. Only option D has all three parts correct: column = name, table = Students, filter = grade = 11.完整的 SELECT 需要:SELECT <列> FROM <表> WHERE <条件>。只有选项 D 三个部分都正确:列 = name,表 = Students,过滤 = grade = 11。
SQL SELECT syntax: SELECT columns FROM table WHERE condition;. You must include FROM to name the table. Option A has no WHERE. Options B and C are missing FROM or SELECT columns.SQL SELECT 语法:SELECT 列 FROM 表 WHERE 条件;。必须包含 FROM 来命名表。选项 A 没有 WHERE。选项 B 和 C 缺少 FROM 或 SELECT 列。
In SQL, ORDER BY score DESC sorts the results in what order?在 SQL 中,ORDER BY score DESC 以什么顺序排序结果?
§5 · Q2
Lowest score first最低分在前
Highest score first最高分在前
Alphabetical order字母顺序
Random order随机顺序
DESC stands for descending: highest to lowest. ASC (ascending) is lowest to highest and is the default. So ORDER BY score DESC puts the highest score first in the result set.DESC 代表降序,即从高到低。ASC(升序)从低到高,是默认值。所以 ORDER BY score DESC 将最高分放在结果集的第一位。
DESC = descending = highest first. ASC = ascending = lowest first (default). ORDER BY does not produce alphabetical or random ordering unless the column contains strings (for alphabetical) or you use RANDOM().DESC = 降序 = 最高在前。ASC = 升序 = 最低在前(默认)。除非列包含字符串(字母顺序)或使用 RANDOM(),否则 ORDER BY 不产生字母或随机顺序。
Exam tip考试提示

Write the full statement in clause order: SELECT, FROM, JOIN ... ON, WHERE, GROUP BY, ORDER BY. In a JOIN name the table in front of any column that both tables have, and state which key equals which. When you predict output, list the rows in the order the query asks for. Common errors: = NULL instead of IS NULL, forgetting that COUNT(*) and COUNT(column) differ, and leaving out FROM.

按子句顺序写出完整语句:SELECT、FROM、JOIN ... ON、WHERE、GROUP BY、ORDER BY。使用 JOIN 时,两个表都有的列要在前面写上表名,并说明哪个键等于哪个键。预测输出时,按查询要求的顺序列出各行。常见错误:用 = NULL 代替 IS NULL,忘记 COUNT(*) 与 COUNT(列) 不同,以及漏写 FROM。

Check your understanding自我检测
What does SELECT name FROM Students WHERE grade = 11 ORDER BY name DESC; return for the Students table of Worked Example 7?对于例题 7 的 Students 表,SELECT name FROM Students WHERE grade = 11 ORDER BY name DESC; 返回什么?

Grade 11 has Alice and Bob. Descending alphabetical order puts Bob first: the rows are Bob, then Alice.

11 年级有 Alice 和 Bob。按字母降序排列时 Bob 在前:结果依次为 Bob、Alice。

What does SELECT COUNT(*) FROM Scores WHERE subject = 'Math'; return, and which rows does it count?SELECT COUNT(*) FROM Scores WHERE subject = 'Math'; 返回什么?它统计的是哪些行?

It returns 2: the rows with score_id 1 (Alice, 92) and score_id 3 (Bob, 78).

返回 2:score_id 为 1(Alice,92)和 score_id 为 3(Bob,78)的两行。

Write the JOIN query that gives each student's name and score for CS only, lowest score first, and give its result.写出只给出 CS 科目每位学生姓名和成绩、成绩低的在前的 JOIN 查询,并给出其结果。

SELECT Students.name, Scores.score FROM Scores JOIN Students ON Scores.student_id = Students.student_id WHERE Scores.subject = 'CS' ORDER BY Scores.score; The result is Alice 88 and then Carol 95.

SELECT Students.name, Scores.score FROM Scores JOIN Students ON Scores.student_id = Students.student_id WHERE Scores.subject = 'CS' ORDER BY Scores.score; 结果为 Alice 88,然后是 Carol 95。


HTML and the Web: An IntroductionHTML 与网络:入门介绍

Learning objectives学习目标
  • Describe the structure of an HTML page (doctype, head, body) and what the browser does with the file.
  • Write headings, paragraphs, links, lists and tables with correctly paired and nested tags.
  • Generate HTML from program data and escape the characters &, < and > so they display as text.
  • 描述 HTML 页面的结构(文档类型、head、body)以及浏览器如何处理该文件。
  • 用正确成对、正确嵌套的标签编写标题、段落、链接、列表和表格。
  • 根据程序数据生成 HTML,并对字符 &、< 和 > 进行转义,使其显示为文本。
HTML in four facts.HTML 的四个要点。
  • HTML = HyperText Markup LanguageHTML = 超文本标记语言: the standard language for creating web pages. A browser reads an HTML file and renders it visually. Alberta CSE1210: "Students are introduced to Internet computing through the use of one or more Web-specific markup languages.":创建网页的标准语言。浏览器读取 HTML 文件并将其可视化渲染。阿尔伯塔 CSE1210:"学生通过使用一种或多种网络专用标记语言了解互联网计算。"
  • Tags标签: HTML uses paired tags: <tag>content</tag>. Opening tag + content + closing tag. Self-closing tags (e.g. <br>, <img>) have no content.:HTML 使用成对标签:<标签>内容</标签>。开始标签 + 内容 + 结束标签。自闭合标签(如 <br>、<img>)没有内容。
  • Structure: head + body结构:head + body: every HTML page has a <head> (metadata: title, charset, links to CSS) and a <body> (visible content).:每个 HTML 页面都有一个 <head>(元数据:标题、字符集、CSS 链接)和一个 <body>(可见内容)。
  • Key tags to know需要了解的关键标签: <h1>–<h6> headings, <p> paragraph, <a href="..."> link, <ul>/<li> list, <table> table, <form> form, <input> input field.:<h1>–<h6> 标题,<p> 段落,<a href="..."> 链接,<ul>/<li> 列表,<table> 表格,<form> 表单,<input> 输入框。
Worked Example 11: A minimal HTML page displaying a data table例题 11:显示数据表的最小 HTML 页面

Write an HTML page that displays the Students table from §4 as a formatted web table.编写一个 HTML 页面,将 §4 的 Students 表显示为格式化的网页表格。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Student Records</title>
</head>
<body>
  <h1>Students</h1>
  <table border="1">
    <tr>
      <th>ID</th><th>Name</th><th>Grade</th>
    </tr>
    <tr><td>1</td><td>Alice</td><td>11</td></tr>
    <tr><td>2</td><td>Bob</td><td>11</td></tr>
    <tr><td>3</td><td>Carol</td><td>12</td></tr>
  </table>
</body>
</html>

<!DOCTYPE html> declares the document type as HTML5; <head> holds metadata (<meta charset="UTF-8"> sets the character encoding; <title> sets the browser-tab title); <body> contains the visible content; <table> creates a table; <tr> is a table row; <th> is a header cell; <td> is a data cell.<!DOCTYPE html> 声明文档类型为 HTML5;<head> 含元数据(<meta charset="UTF-8"> 设置字符编码,<title> 设置浏览器标签标题);<body> 含可见内容;<table> 创建表格;<tr> 是表格行(table row);<th> 是表头单元格(table header);<td> 是普通数据单元格(table data)。

Worked Example 12: Generating a list from data, and escaping special characters例题 12:根据数据生成列表,并转义特殊字符

A program holds the club names "R&D Club" and "Chess <Junior>". Produce the list items for a web page, and explain what the browser would do if the special characters were not escaped.程序中有社团名称 "R&D Club" 和 "Chess <Junior>"。为网页生成列表项,并说明如果不转义特殊字符,浏览器会怎么做。

Step 1: generate the items. HTML gives & and < special meanings (the start of a character reference, the start of a tag), so text that contains them is converted by html.escape first.第 1 步:生成列表项。HTML 赋予 & 和 < 特殊含义(字符引用的开始、标签的开始),所以含有它们的文本要先用 html.escape 转换。

import html

clubs = ["R&D Club", "Chess <Junior>"]
for name in clubs:
    print(f"<li>{html.escape(name)}</li>")

# Output:
# <li>R&amp;D Club</li>
# <li>Chess &lt;Junior&gt;</li>

Step 2: place the items in a page. The generated lines go inside a <ul>; the paragraph shows a link with <a href>. Every tag opened is closed in reverse order.第 2 步:把列表项放入页面。生成的行放在 <ul> 内;段落中用 <a href> 显示一个链接。每个打开的标签都按相反的顺序关闭。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Clubs</title>
</head>
<body>
  <h2>Clubs</h2>
  <p>See the <a href="schedule.html">schedule</a>.</p>
  <ul>
    <li>R&amp;D Club</li>
    <li>Chess &lt;Junior&gt;</li>
  </ul>
</body>
</html>

The browser shows the heading Clubs, the sentence with a clickable link, and a bullet list reading "R&D Club" and "Chess <Junior>" with the original characters restored. Without escaping, the browser would read <Junior> as a tag it does not know and drop it, so the second item would display only as "Chess", and a bare & can be misread as the start of a character reference. Escaping also matters for security: text from users must never be inserted into a page as raw markup.浏览器会显示标题 Clubs、带可点击链接的句子,以及内容为“R&D Club”和“Chess <Junior>”的项目符号列表,原来的字符都被还原。如果不转义,浏览器会把 <Junior> 当作一个不认识的标签而丢弃,第二项就只显示为“Chess”,而单独的 & 也可能被误读为字符引用的开头。转义对安全也很重要:来自用户的文本绝不能作为原始标记插入页面。

In HTML, what does <a href="https://example.com">Click here</a> create?在 HTML 中,<a href="https://example.com">点击这里</a> 创建什么?
§6 · Q1
An image from the URL来自该 URL 的图片
A clickable hyperlink to example.com with text "Click here"指向 example.com 的可点击超链接,文本为"点击这里"
A form that submits to example.com提交到 example.com 的表单
A paragraph with the URL as text以 URL 为文本的段落
The <a> tag (anchor) creates a hyperlink. The href attribute specifies the destination URL. The content between the tags ("Click here") is the visible link text. Clicking it navigates to example.com.<a> 标签(锚点)创建超链接。href 属性指定目标 URL。标签之间的内容("点击这里")是可见的链接文本。点击它导航到 example.com。
The <a> tag with href creates a hyperlink, not an image (<img>), form (<form>), or paragraph (<p>).<a> 标签加 href 创建超链接,不是图片(<img>)、表单(<form>)或段落(<p>)。
Which HTML section contains the page's visible content (headings, paragraphs, tables)?哪个 HTML 部分包含页面的可见内容(标题、段落、表格)?
§6 · Q2
<body>
<head>
<title>
<meta>
The <body> element contains all visible page content. The <head> holds metadata (title, charset, CSS links; not rendered as page content). <title> sets the browser tab title (shown in the tab, not the page). <meta> provides machine-readable metadata.<body> 元素包含所有可见的页面内容。<head> 存放元数据(标题、字符集、CSS 链接,不渲染为页面内容)。<title> 设置浏览器标签标题(显示在标签中,不在页面上)。<meta> 提供机器可读的元数据。
body = visible content. head = metadata (not visible as page content). title = browser tab text. meta = machine-readable metadata.body = 可见内容。head = 元数据(不作为页面内容可见)。title = 浏览器标签文本。meta = 机器可读元数据。
Exam tip考试提示

In a "find the error" HTML question, check four things in order: every opening tag has a closing tag, tags close in reverse order of opening, attribute values are in quotes, and visible content is in the body while metadata is in the head. Say what the browser would show, not only what is wrong. Common errors: crossing tags (<p><b>...</p></b>) and putting content in the head.

在“找出错误”的 HTML 题中,依次检查四点:每个开始标签都有结束标签,标签按开启的相反顺序关闭,属性值带引号,可见内容在 body 中而元数据在 head 中。要说明浏览器会显示什么,而不只是错在哪里。常见错误:标签交叉(<p><b>...</p></b>)以及把内容放进 head。

Check your understanding自我检测
Write the HTML for a link with the text Example that goes to https://example.com.写出文本为 Example、指向 https://example.com 的链接的 HTML。

<a href="https://example.com">Example</a>. The href attribute holds the address and the text between the tags is what the reader clicks.

<a href="https://example.com">Example</a>。href 属性存放地址,标签之间的文本是读者点击的内容。

What does html.escape("5 < 7") return, and why is that needed before the text goes into a page?html.escape("5 < 7") 返回什么?为什么文本放入页面前需要这样做?

It returns 5 &lt; 7. The browser turns &lt; back into a visible <; a raw < could be read as the start of a tag.

返回 5 &lt; 7。浏览器会把 &lt; 还原成可见的 <;原始的 < 可能被当作标签的开头。

Find the error in <p>Hello <b>world</p></b> and correct it.找出 <p>Hello <b>world</p></b> 中的错误并改正。

The tags cross: <b> was opened last, so it must close first. Correct: <p>Hello <b>world</b></p>.

标签交叉了:<b> 最后打开,所以必须最先关闭。正确写法:<p>Hello <b>world</b></p>。


Data on the Web: JSON and APIs网络上的数据:JSON 与接口

Learning objectives学习目标
  • Convert between JSON text and Python values with json.loads and json.dumps, including null and None, true and True.
  • Read nested JSON by chaining keys and list indexes, and spot invalid JSON (single quotes, unquoted keys, trailing commas).
  • Describe how a web request travels from a browser through a server to a database and back as a JSON response.
  • 用 json.loads 和 json.dumps 在 JSON 文本与 Python 值之间转换,包括 null 与 None、true 与 True。
  • 通过连续使用键和列表索引读取嵌套 JSON,并识别无效 JSON(单引号、不带引号的键、尾随逗号)。
  • 描述一个网络请求如何从浏览器经服务器到达数据库,再以 JSON 响应返回。
JSON and API in four facts.JSON 和接口的四个要点。
  • JSON = JavaScript Object NotationJSON = JavaScript 对象表示法: a lightweight text format for storing and transmitting structured data. Looks like Python dictionaries and lists. Human-readable and machine-parseable. CSTA 3A-DA-12: "Create computational models that represent the relationships among different elements of data"; JSON is how those models travel over the web.:用于存储和传输结构化数据的轻量级文本格式。看起来像 Python 字典和列表。人类可读且机器可解析。CSTA 3A-DA-12:"创建表示数据不同元素之间关系的计算模型";JSON 就是这些模型在网络上传输的方式。
  • JSON syntaxJSON 语法: keys must be double-quoted strings; values can be strings, numbers, booleans (true/false), null, arrays ([]), or nested objects ({}).:键必须是双引号字符串;值可以是字符串、数字、布尔值(true/false)、null、数组([])或嵌套对象({})。
  • API = Application Programming Interface接口 = 应用程序编程接口: a set of rules that lets one program request data or actions from another. Web APIs expose data over HTTP; the response is usually JSON. Alberta CSE2210/3210 (Client-side Scripting) and AB CSE1220 introduce this web-programming context.:让一个程序向另一个程序请求数据或操作的一组规则。Web 接口通过 HTTP 暴露数据;响应通常是 JSON。阿尔伯塔 CSE2210/3210(客户端脚本)和 AB CSE1220 介绍这种网页编程背景。
  • Python: json modulePython:json 模块: json.loads(text) parses a JSON string into a Python dict/list; json.dumps(obj) serialises a Python object back to a JSON string.:json.loads(text) 将 JSON 字符串解析为 Python 字典/列表;json.dumps(obj) 将 Python 对象序列化回 JSON 字符串。
Worked Example 13: Parsing a JSON API response in Python例题 13:在 Python 中解析 JSON 接口响应

A weather API returns this JSON response. Extract the city name and temperature and print them.天气接口返回以下 JSON 响应。提取城市名称和温度并打印。

Sample JSON response (the text the API sends back).示例 JSON 响应(接口返回的文本)。

{
  "city": "Toronto",
  "country": "CA",
  "temperature": 22.4,
  "humidity": 65,
  "conditions": ["cloudy", "mild"],
  "forecast": {
    "tomorrow": "rain",
    "temp_high": 18.0
  }
}

Python: parse and extract fields.Python:解析并提取字段。

import json

# Simulated API response text
response_text = '''
{
  "city": "Toronto",
  "country": "CA",
  "temperature": 22.4,
  "humidity": 65,
  "conditions": ["cloudy", "mild"],
  "forecast": {"tomorrow": "rain", "temp_high": 18.0}
}
'''

# Parse JSON string into a Python dictionary
data = json.loads(response_text)

# Access fields
city = data["city"]
temp = data["temperature"]
tomorrow = data["forecast"]["tomorrow"]

print(f"{city}: {temp}°C, tomorrow: {tomorrow}")
# Output: Toronto: 22.4°C, tomorrow: rain

import json loads the json module; json.loads(...) parses a JSON string into a Python dictionary (loads = load string); data["city"] accesses a value by key; data["forecast"]["tomorrow"] accesses a nested object by first retrieving the "forecast" dictionary, then its "tomorrow" key.import json 导入 json 模块;json.loads(...) 将 JSON 字符串(loads = load string)转为 Python 字典;data["city"] 通过键访问字典值;data["forecast"]["tomorrow"] 访问嵌套对象:先取 "forecast" 字典,再取其 "tomorrow" 键。

Browser浏览器 Web server网络服务器 Database数据库 1. request1. 请求 2. SQL query2. SQL 查询 3. rows3. 数据行 4. JSON4. JSON 1 GET /scores?student=11 GET /scores?student=1 2 SELECT score FROM Scores WHERE student_id = 1;2 SELECT score FROM Scores WHERE student_id = 1; 3 rows: 92, 883 行:92、88 4 {"scores": [92, 88]}4 {"scores": [92, 88]}
Figure 2. One web request for Alice's scores (student_id 1 from Worked Example 7). Follow the numbered arrows: the browser asks the server (1), the server asks the database in SQL (2), the database returns the matching rows 92 and 88 (3), and the server sends them back to the browser as JSON text (4). The browser never queries the database directly.图 2. 为查询 Alice 的成绩(例题 7 中 student_id 为 1)而发出的一次网络请求。沿着编号箭头阅读:浏览器向服务器发出请求 (1),服务器用 SQL 向数据库查询 (2),数据库返回匹配的行 92 和 88 (3),服务器再以 JSON 文本把它们发回浏览器 (4)。浏览器从不直接查询数据库。
Worked Example 14: Building JSON and rejecting invalid JSON例题 14:生成 JSON 并拒绝无效 JSON

A server stores a student as a Python dictionary. (a) Convert it to JSON text and back, and check how None and True are written. (b) Show what happens when the text uses single quotes.服务器把一名学生存储为 Python 字典。(a) 把它转换为 JSON 文本再转换回来,并检查 None 和 True 是如何写的。(b) 说明文本使用单引号时会发生什么。

(a) dumps then loads. json.dumps turns a Python value into JSON text (a str); json.loads parses the text back into Python values.(a) 先 dumps 再 loads。json.dumps 把 Python 值转换为 JSON 文本(str);json.loads 把文本解析回 Python 值。

import json

student = {"name": "Bob", "grade": 11, "scores": [78, 85, 91], "club": None, "active": True}
text = json.dumps(student)
print(text)

back = json.loads(text)
print(back["scores"][2], back["club"], back["active"])

try:
    json.loads("{'name': 'Bob'}")
except json.JSONDecodeError as error:
    print("Invalid JSON:", error.msg)

# Output:
# {"name": "Bob", "grade": 11, "scores": [78, 85, 91], "club": null, "active": true}
# 91 None True
# Invalid JSON: Expecting property name enclosed in double quotes

In the JSON text the keys and strings are in double quotes, None became null and True became true (lower case). After json.loads they are None and True again, and back["scores"][2] is 91: the key picks the list, the index 2 picks its third item.在 JSON 文本中,键和字符串使用双引号,None 变成了 null,True 变成了 true(小写)。经过 json.loads 后又变回 None 和 True,而 back["scores"][2] 是 91:键选出列表,索引 2 选出其中的第三项。

(b) Invalid JSON. The text {'name': 'Bob'} is a valid Python dictionary but not valid JSON, because JSON allows only double-quoted keys and strings. json.loads raises json.JSONDecodeError, and the program above catches it and prints the reason (the exact wording is Python's). A server that receives such text should report an error instead of guessing.(b) 无效 JSON。文本 {'name': 'Bob'} 是合法的 Python 字典,但不是合法的 JSON,因为 JSON 只允许使用双引号的键和字符串。json.loads 会引发 json.JSONDecodeError,上面的程序捕获它并打印原因(具体措辞由 Python 决定)。收到这类文本的服务器应当报告错误,而不是去猜测。

In JSON, which of the following is a valid key-value pair?在 JSON 中,以下哪个是有效的键值对?
§7 · Q1
name: "Alice"
'name': 'Alice'
name = "Alice"
"name": "Alice"
In JSON, keys must be double-quoted strings. Values must also use double quotes (not single quotes). So only "name": "Alice" is valid JSON. Single quotes and unquoted keys are not allowed in JSON (though they are valid in Python dicts and JavaScript objects).在 JSON 中,键必须是双引号字符串。值也必须使用双引号(不是单引号)。因此只有 "name": "Alice" 是有效的 JSON。单引号和不带引号的键在 JSON 中不被允许(尽管在 Python 字典和 JavaScript 对象中有效)。
JSON requires double-quoted keys and double-quoted string values. No single quotes, no unquoted keys, no equals signs. Only option D follows all three rules.JSON 要求双引号键和双引号字符串值。不允许单引号、不带引号的键或等号。只有选项 D 遵循所有三条规则。
Given data = {"scores": [88, 92, 75]} in Python, what does data["scores"][1] evaluate to?给定 Python 中 data = {"scores": [88, 92, 75]},data["scores"][1] 的值是什么?
§7 · Q2
92
88
75
Error: you cannot index a list inside a dict错误:不能索引字典内的列表
data["scores"] accesses the list [88, 92, 75]. Then [1] accesses index 1 of that list. Python lists are 0-indexed, so index 0 = 88, index 1 = 92, index 2 = 75. Result: 92.data["scores"] 访问列表 [88, 92, 75]。然后 [1] 访问该列表的索引 1。Python 列表从 0 开始索引,所以索引 0 = 88,索引 1 = 92,索引 2 = 75。结果:92。
Two steps: (1) data["scores"] returns the list [88, 92, 75]. (2) [1] on that list returns the item at index 1. Python is 0-indexed: index 0 = 88, index 1 = 92.两步:(1) data["scores"] 返回列表 [88, 92, 75]。(2) 对该列表 [1] 返回索引 1 处的项。Python 从 0 开始索引:索引 0 = 88,索引 1 = 92。
Exam tip考试提示

When a question gives JSON, trace the access path one step at a time: the key chooses a value, an index chooses a list item, and the next key goes inside an object. To judge validity, check double quotes, no trailing comma, and lower-case true, false and null. Common errors: counting list positions from 1 instead of 0, and writing Python's True or None inside JSON.

题目给出 JSON 时,一步一步追踪访问路径:键选出一个值,索引选出列表中的一项,下一个键则进入对象内部。判断有效性时,检查双引号、没有尾随逗号,以及小写的 true、false 和 null。常见错误:列表位置从 1 而不是 0 开始数,以及在 JSON 中写 Python 的 True 或 None。

Check your understanding自我检测
What does json.dumps({"ok": True, "n": None}) return?json.dumps({"ok": True, "n": None}) 返回什么?

The string {"ok": true, "n": null}: Python's True and None are written as true and null.

字符串 {"ok": true, "n": null}:Python 的 True 和 None 被写成 true 和 null。

If data = json.loads('{"a": {"b": [10, 20]}}'), what is data["a"]["b"][1]?如果 data = json.loads('{"a": {"b": [10, 20]}}'),那么 data["a"]["b"][1] 是多少?

20. data["a"] is the inner object, ["b"] is the list [10, 20], and index 1 is its second item.

20。data["a"] 是内层对象,["b"] 是列表 [10, 20],索引 1 是它的第二项。

In Figure 2, which of the four steps carries SQL and which carries JSON?在图 2 中,四个步骤里哪一步传送 SQL,哪一步传送 JSON?

Step 2 (server to database) carries the SQL query, and step 4 (server to browser) carries the JSON response. The browser never talks to the database directly.

第 2 步(服务器到数据库)传送 SQL 查询,第 4 步(服务器到浏览器)传送 JSON 响应。浏览器从不直接访问数据库。


Exam Strategy and Common Pitfalls考试策略与常见陷阱

Data and file questions (§1–§3)数据和文件题(§1–§3)
  • Data vs information distinction.数据与信息的区别。 Questions often ask: "Is this data or information? Explain." The answer hinges on context: raw unlabelled values are data; values with meaning attached (label, unit, interpretation) are information. State the difference explicitly.题目常问:"这是数据还是信息?请解释。"答案取决于上下文:未标注的原始值是数据;附有含义(标签、单位、解释)的值是信息。明确说明区别。
  • CSV type-conversion pitfall.CSV 类型转换陷阱。 Every value read from a CSV is a string. Always convert with int() or float() before numeric comparison or arithmetic. Forgetting this is the single most common file-processing bug.从 CSV 读取的每个值都是字符串。在数值比较或算术之前,始终用 int() 或 float() 转换。忘记这一点是最常见的文件处理错误。
  • File modes.文件模式。 Know "r" (read), "w" (write, which overwrites), "a" (append). If a question says "add a new record without deleting existing ones," the answer is append mode ("a").了解 "r"(读取)、"w"(写入,会覆盖)、"a"(追加)。如果题目说"添加新记录而不删除现有记录",答案是追加模式("a")。
Database and SQL questions (§4–§5)数据库和 SQL 题(§4–§5)
  • Primary vs foreign key.主键与外键。 Primary key = unique identifier for rows in its own table. Foreign key = references the primary key in another table. Mixing these up is a common error. Remember: foreign key creates the link between tables.主键 = 本表行的唯一标识符。外键 = 引用另一个表的主键。混淆这两者是常见错误。记住:外键创建表之间的链接。
  • SQL clause order.SQL 子句顺序。 Always: SELECT → FROM → WHERE → ORDER BY. You cannot write WHERE before FROM. Missing FROM is a very common SQL syntax error.始终:SELECT → FROM → WHERE → ORDER BY。不能在 FROM 之前写 WHERE。缺少 FROM 是很常见的 SQL 语法错误。
  • Ontario divergence.安大略分流。 If you are in ICS4U (university stream), SQL is ICS4C (college stream) content, and the ICS4U standard does not name SQL. Your file I/O standard is A3.1. Know which course you are in.如果你在 ICS4U(大学流),SQL 是 ICS4C(学院流)内容,ICS4U 的标准没有提到 SQL。你的文件读写标准是 A3.1。了解你在哪门课程中。
HTML and JSON questions (§6–§7)HTML 和 JSON 题(§6–§7)
  • Paired tags.成对标签。 Every opening tag needs a closing tag (except self-closing ones like <br>). In a "find the error in this HTML" question, a missing closing tag is a common bug.每个开始标签都需要一个结束标签(除了 <br> 等自闭合标签)。在"找出 HTML 中的错误"题中,缺少结束标签是常见的错误。
  • JSON double quotes only.JSON 只用双引号。 JSON keys and string values must use double quotes, not single quotes. On a "is this valid JSON?" question, single quotes or unquoted keys make it invalid.JSON 键和字符串值必须使用双引号,而非单引号。在"这是有效的 JSON 吗?"题中,单引号或不带引号的键使其无效。
  • data vs information for AP CSP.AP CSP 的数据与信息。 AP CSP Big Idea 2 covers how programs can extract knowledge from raw data. When a question shows a JSON payload and asks "what knowledge can be generated from this data?", apply the data → information transformation from §1.AP CSP 大概念 2 涵盖程序如何从原始数据中提取知识。当题目展示 JSON 载荷并问"可以从这些数据中生成什么知识?"时,应用 §1 的数据 → 信息转换。
Answer hygiene作答规范
  • State the tradeoff explicitly.明确说明权衡。 CSTA 3A-DA-10 says to "evaluate tradeoffs." On a question about CSV vs database, do not just say "databases are better." State both sides: CSV is simpler and portable; a database supports complex queries and avoids duplicate data. Then state the recommendation for the given scenario.CSTA 3A-DA-10 要求"评估权衡"。在关于 CSV 与数据库的题中,不要只说"数据库更好"。说明两方面:CSV 更简单且可移植;数据库支持复杂查询并避免数据重复。然后针对给定场景说明建议。
  • Show the full SQL statement.展示完整的 SQL 语句。 On SQL questions, always write the complete statement including SELECT, FROM, and (if required) WHERE. A partial statement is an incomplete answer.在 SQL 题中,始终写出完整语句,包括 SELECT、FROM 和(如需)WHERE。不完整的语句是不完整的答案。

Flashcards闪卡

0 / 14 flipped0 / 14 已翻
Data vs Information数据与信息
Data = raw facts without context (e.g., 98.6). Information = data with meaning attached (e.g., "body temperature 98.6°F, normal"). CSTA 3A-DA-10/11/12.数据 = 没有上下文的原始事实(如 98.6)。信息 = 附有含义的数据(如"体温 98.6°F,正常")。CSTA 3A-DA-10/11/12。
Python file modesPython 文件模式
"r" = read only. "w" = write (overwrites). "a" = append (adds to end). Use with open(...) as f: to auto-close. AB CSE2130 outcomes 1.4.2, 1.4.5."r" = 只读。"w" = 写入(覆盖)。"a" = 追加(在末尾添加)。使用 with open(...) as f: 自动关闭。AB CSE2130 结果 1.4.2、1.4.5。
CSV header rowCSV 标题行
The first row of a CSV that names each column. Use csv.DictReader to auto-map rows to column names. All CSV values are read as strings, so convert with int() or float() before math.命名每列的 CSV 第一行。使用 csv.DictReader 将行自动映射到列名。所有 CSV 值都作为字符串读取,所以在数学运算前用 int() 或 float() 转换。
Relational database关系数据库
A database that organises data in linked tables. Tables are joined by primary keys (unique row IDs) and foreign keys (references to another table's primary key). CSTA 3A-DA-10.将数据组织在关联表中的数据库。表通过主键(唯一行 ID)和外键(对另一个表主键的引用)连接。CSTA 3A-DA-10。
Primary key主键
A column whose value uniquely identifies each row in a table. No two rows may share the same primary key value.其值唯一标识表中每行的列。任何两行不得共享相同的主键值。
Foreign key外键
A column in one table that references the primary key of another table. Creates the relational link between tables.一个表中引用另一个表主键的列。创建表之间的关系链接。
SQL SELECT syntaxSQL SELECT 语法
SELECT columns FROM table WHERE condition ORDER BY column DESC; Always: SELECT → FROM → WHERE → ORDER BY. Missing FROM is a very common SQL error.SELECT 列 FROM 表 WHERE 条件 ORDER BY 列 DESC; 始终:SELECT → FROM → WHERE → ORDER BY。缺少 FROM 是很常见的 SQL 错误。
SQL WHERE clauseSQL WHERE 子句
Filters rows. Only rows where the condition is true are returned. Operators: =, <, >, !=, LIKE, AND, OR. E.g., WHERE score > 85 AND grade = 11.过滤行。只返回条件为真的行。运算符:=、<、>、!=、LIKE、AND、OR。例如:WHERE score > 85 AND grade = 11。
HTML structureHTML 结构
<html> contains <head> (metadata: title, charset, CSS) and <body> (visible content). Every tag has an opening and closing form except self-closing tags like <br> and <img>.<html> 包含 <head>(元数据:标题、字符集、CSS)和 <body>(可见内容)。每个标签都有开始和结束形式,除了 <br> 和 <img> 等自闭合标签。
HTML table tagsHTML 表格标签
<table> wraps the table. <tr> = table row. <th> = header cell (bold). <td> = data cell. Nest: table > tr > th/td.<table> 包裹表格。<tr> = 表格行。<th> = 表头单元格(粗体)。<td> = 数据单元格。嵌套:table > tr > th/td。
JSON format rulesJSON 格式规则
Keys must be double-quoted strings. Values can be strings, numbers, booleans (true/false), null, arrays [], or objects {}. No single quotes. No trailing commas.键必须是双引号字符串。值可以是字符串、数字、布尔值(true/false)、null、数组 [] 或对象 {}。不允许单引号。不允许尾随逗号。
json.loads() vs json.dumps()json.loads() 与 json.dumps()
json.loads(text) = parse JSON string → Python dict/list. json.dumps(obj) = serialise Python dict/list → JSON string. "loads" = load string; "dumps" = dump string.json.loads(text) = 解析 JSON 字符串 → Python 字典/列表。json.dumps(obj) = 序列化 Python 字典/列表 → JSON 字符串。"loads" = 加载字符串;"dumps" = 转储字符串。
API (web context)接口(网络背景)
Application Programming Interface. A set of rules that lets one program request data from another over HTTP. Response is usually JSON. AB CSE1210/1220/2210/3210 web scripting pathway.应用程序编程接口。让一个程序通过 HTTP 向另一个程序请求数据的一组规则。响应通常是 JSON。AB CSE1210/1220/2210/3210 网页脚本路径。
AP CSP Big Idea 2 (DAT)AP CSP 大概念 2(DAT)
Data is central to computing: it communicates initial conditions and represents new knowledge. Topics 2.3 (extracting information from data) and 2.4 (using programs with data).数据是计算的核心:它传递初始条件并代表新知识。主题 2.3(从数据中提取信息)和 2.4(将程序与数据结合使用)。

Practice Quiz综合测验

A program reads the number 37 from a CSV file. What Python type does the variable hold immediately after reading?程序从 CSV 文件中读取数字 37。读取后变量立即持有什么 Python 类型?
Q1
int整数 int
float浮点数 float
str字符串 str
bool布尔值 bool
CSV files are plain text. Every value read from a CSV, including numbers, is a string (str) until you convert it. Use int(row["score"]) or float(row["score"]) before doing math.CSV 文件是纯文本。从 CSV 读取的每个值(包括数字)都是字符串(str),直到你转换它。在进行数学运算之前使用 int(row["score"]) 或 float(row["score"])。
CSV values are always strings. Python does not auto-convert CSV text to int or float. You must call int() or float() explicitly.CSV 值始终是字符串。Python 不会自动将 CSV 文本转换为 int 或 float。必须显式调用 int() 或 float()。
A Students table has columns student_id, name, grade. A Scores table has columns score_id, student_id, subject, score. What is student_id called in the Scores table?Students 表有列 student_id、name、grade。Scores 表有列 score_id、student_id、subject、score。student_id 在 Scores 表中叫什么?
Q2
Primary key主键
Foreign key外键
Index索引
Header标题
In the Scores table, student_id references the primary key of the Students table. A column that references another table's primary key is a foreign key. It creates the relational link between the two tables.在 Scores 表中,student_id 引用 Students 表的主键。引用另一个表主键的列是外键。它创建两个表之间的关系链接。
In the Scores table, student_id is a foreign key (it references Students.student_id). The primary key of Scores is score_id (the unique identifier for each row in Scores).在 Scores 表中,student_id 是外键(它引用 Students.student_id)。Scores 的主键是 score_id(Scores 中每行的唯一标识符)。
Which SQL query returns the names of all students in grade 12, sorted alphabetically?哪个 SQL 查询返回所有 12 年级学生的姓名,按字母顺序排列?
Q3
SELECT * WHERE grade = 12 ORDER BY name;
SELECT name FROM Students grade = 12;
SELECT name FROM Students ORDER BY name WHERE grade = 12;
SELECT name FROM Students WHERE grade = 12 ORDER BY name;
Correct SQL clause order: SELECT → FROM → WHERE → ORDER BY. Option D has all four in the right order: SELECT name (column), FROM Students (table), WHERE grade = 12 (filter), ORDER BY name (sort). ASC is the default (alphabetical = ascending).正确的 SQL 子句顺序:SELECT → FROM → WHERE → ORDER BY。选项 D 四个都按正确顺序:SELECT name(列),FROM Students(表),WHERE grade = 12(过滤),ORDER BY name(排序)。ASC 是默认值(字母顺序 = 升序)。
SQL clause order is fixed: SELECT → FROM → WHERE → ORDER BY. Missing FROM (option A), missing WHERE keyword (option B), and wrong ORDER BY position (option C) all make those queries invalid.SQL 子句顺序是固定的:SELECT → FROM → WHERE → ORDER BY。缺少 FROM(选项 A)、缺少 WHERE 关键字(选项 B)和 ORDER BY 位置错误(选项 C)都使这些查询无效。
In HTML, which tag creates a hyperlink to another page?在 HTML 中,哪个标签创建指向另一页面的超链接?
Q4
<a href="url">
<link href="url">
<src="url">
<p href="url">
The <a> (anchor) tag with the href attribute creates a hyperlink. <link> is used in the <head> to link external CSS stylesheets. <p> is a paragraph. There is no <src> tag.<a>(锚点)标签加 href 属性创建超链接。<link> 在 <head> 中用于链接外部 CSS 样式表。<p> 是段落。没有 <src> 标签。
Hyperlinks use the anchor tag: <a href="url">text</a>. The <link> tag in the head links CSS files, not navigational hyperlinks.超链接使用锚点标签:<a href="url">文本</a>。head 中的 <link> 标签链接 CSS 文件,不是导航超链接。
A JSON object is {"name": "Bob", "scores": [78, 85, 91]}. What does data["scores"][2] evaluate to in Python?JSON 对象为 {"name": "Bob", "scores": [78, 85, 91]}。在 Python 中 data["scores"][2] 的值是什么?
Q5
78
85
91
Error错误
data["scores"] returns the list [78, 85, 91]. Python lists are 0-indexed: index 0 = 78, index 1 = 85, index 2 = 91. So data["scores"][2] = 91.data["scores"] 返回列表 [78, 85, 91]。Python 列表从 0 开始索引:索引 0 = 78,索引 1 = 85,索引 2 = 91。所以 data["scores"][2] = 91。
Python is 0-indexed. data["scores"] = [78, 85, 91]. Index 0 = 78, index 1 = 85, index 2 = 91.Python 从 0 开始索引。data["scores"] = [78, 85, 91]。索引 0 = 78,索引 1 = 85,索引 2 = 91。
Which CSTA standard says "Create interactive data visualizations using software tools to help others better understand real-world phenomena"? 🇺🇸 CSTA哪个 CSTA 标准说"使用软件工具创建互动数据可视化,以帮助他人更好地理解现实世界现象"?🇺🇸 CSTA
Q6
3A-DA-10
3A-DA-11
3A-DA-12
3B-DA-05
CSTA 3A-DA-11 (verbatim): "Create interactive data visualizations using software tools to help others better understand real-world phenomena." 3A-DA-10 is about data storage tradeoffs. 3A-DA-12 is about computational models of relationships.CSTA 3A-DA-11(原文):"使用软件工具创建互动数据可视化,以帮助他人更好地理解现实世界现象。"3A-DA-10 关于数据存储权衡。3A-DA-12 关于关系的计算模型。
3A-DA-10 = data storage/organisation tradeoffs. 3A-DA-11 = interactive data visualisation. 3A-DA-12 = computational models of data relationships. 3B-DA-05 = data analysis tools for complex systems.3A-DA-10 = 数据存储/组织权衡。3A-DA-11 = 互动数据可视化。3A-DA-12 = 数据关系的计算模型。3B-DA-05 = 复杂系统的数据分析工具。

Readiness Checklist准备就绪清单

Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。

0 / 11 mastered已掌握 0 / 11

What This Feeds Into本单元的去向

Data, databases and the web are the infrastructure that every modern program rests on. The skills here (reading files, parsing CSV and JSON, querying a database, building a web page) support the data work in AP CSP, the CSTA 3A-DA standards, and the data-handling sections of Ontario's Grade 12 Computer Science courses.数据、数据库和网络是每个现代程序所依赖的基础设施。这里的技能(读取文件、解析 CSV 和 JSON、查询数据库、构建网页)支撑 AP CSP 的数据学习、CSTA 3A-DA 标准和安大略 12 年级计算机科学课程的数据处理部分。

Within High School Computer Science.在 HS Computer Science 内部。

Unit 2 (Programming Fundamentals) gave you variables, data types, and I/O; this unit shows where that data lives on disk and in databases. Unit 5 (Data Structures) shows how to organise data in memory (lists, dictionaries); this unit shows how to persist it on disk or transmit it over the web. Unit 9 (Boolean Logic) underpins the WHERE clause logic you used in §5. The data skills here synthesise material from across the series into a complete pipeline: file → parse → filter → display.第 2 单元(编程基础)给了你变量、数据类型和 I/O;本单元展示这些数据在磁盘和数据库中的存储位置。第 5 单元(数据结构)展示如何在内存中组织数据(列表、字典);本单元展示如何将其持久化到磁盘或通过网络传输。第 9 单元(布尔逻辑)支撑你在 §5 中使用的 WHERE 子句逻辑。这里的数据技能将整个系列的材料综合成一个完整的管线:文件 → 解析 → 过滤 → 显示。

AP CSP and AP CSA connections.AP CSP 与 AP CSA 的衔接。

AP CSP Big Idea 2 (Data, DAT) covers the skills in this guide: extracting information from data (topics 2.3, 2.4), seeing how programs generate knowledge from raw inputs, and weighing tradeoffs in data storage and representation (CSTA 3A-DA-10). The CSV-reading and JSON-parsing patterns in §2, §3, and §7 are the practical skills behind a program that processes data. Students moving to AP CSA will meet data again in Unit 4 (Data Collections), which covers arrays, ArrayList, 2D arrays and reading text files; this unit is background for how data is stored and loaded.AP CSP 大概念 2(数据,DAT)涵盖本指南中的技能:从数据中提取信息(主题 2.3、2.4)、了解程序如何从原始输入生成知识,以及权衡数据存储和表示的利弊(CSTA 3A-DA-10)。§2、§3 和 §7 中的 CSV 读取和 JSON 解析模式,是编写处理数据的程序所需的实践技能。转向 AP CSA 的学生会在第 4 单元(数据集合)再次遇到数据,该单元涵盖数组、ArrayList、二维数组和读取文本文件;本单元是理解数据如何存储和加载的背景知识。

This is the ladder we coach students up: from these high school foundations into AP and IB, and on to first-year university. If you would rather have a guide for the next step than take it on trust, Dingrui Scholars tutors teach exactly this path in one-on-one sessions and small-group classes. A free assessment is the place to start.这正是我们陪伴学生攀登的阶梯:从这些高中基础,迈入 AP 与 IB,再走向大学一年级。如果你希望在下一步有人引路,而不是凭感觉前行,Dingrui Scholars 的导师正是沿着这条路径,以一对一辅导与小班课授课。欢迎从免费评估开始。

Common Questions常见问题

What is the difference between data and information?数据和信息有什么区别?

Data is raw, unprocessed facts and symbols, such as a list of numbers, while information is data that has been processed, organised, or interpreted so it carries meaning. Adding context, like saying a temperature is normal, turns data into information.数据是原始的、未经处理的事实和符号,比如一串数字;信息是经过处理、组织或解释后带有意义的数据。加上上下文,比如说某个体温是正常的,就把数据变成了信息。

What is the difference between a primary key and a foreign key?主键和外键有什么区别?

A primary key is a column whose value uniquely identifies each row in a table, while a foreign key is a column that references the primary key of another table. The foreign key is the relational part that links two tables together.主键是其值能唯一标识表中每一行的列,外键是引用另一张表主键的列。外键正是把两张表关联起来的关系部分。

What do SELECT and WHERE do in SQL?SQL 中的 SELECT 和 WHERE 各做什么?

SELECT chooses which columns to return from a table, while WHERE filters the rows so only those meeting a condition are returned. Together they let you pull exactly the data you need from a relational database.SELECT 选择从表中返回哪些列,WHERE 过滤行,只返回满足条件的那些行。两者配合可以从关系数据库中精确取出你需要的数据。

Syllabus alignment & how to use this guide大纲对照与使用说明

How to use this guide如何使用本指南

Data and databases are treated as a core topic by the US frameworks (CSTA 3A-DA family; AP CSP Big Idea 2). Ontario takes a split approach: file I/O sits in ICS4U (university stream, Grade 12), while SQL and web work sit in ICS4C (college stream). BC covers data mainly in the big-data/privacy and Internet-evolution framing of CIS 11/12, with no dedicated SQL standard. Alberta covers files thoroughly in CSE2130 and has a full web-scripting pathway (CSE1210 to CSE3210), but no SQL module in the CSE cluster. Sections §1–§3 (data, files, CSV) are universal. Sections §4–§5 (relational databases, SQL) map most directly to US CSTA, AP CSP, and ON ICS4C. Sections §6–§7 (HTML, JSON/APIs) align with Alberta web scripting and AP CSP Big Idea 2.美国框架将数据和数据库视为核心主题(CSTA 3A-DA 系列;AP CSP 大概念 2)。安大略采用分流方式:文件读写在 ICS4U(大学预科,12 年级),SQL 和网页工作在 ICS4C(学院预科)。BC 主要在 CIS 11/12 的大数据/隐私和互联网演变框架中涵盖数据,没有专用 SQL 标准。阿尔伯塔在 CSE2130 中详细涵盖文件,并有完整的网页脚本路径(CSE1210 至 CSE3210),但 CSE 群集中没有 SQL 模块。§1–§3(数据、文件、CSV)是通用的。§4–§5(关系数据库、SQL)最直接对应美国 CSTA、AP CSP 和安大略 ICS4C。§6–§7(HTML、JSON/接口)与阿尔伯塔网页脚本和 AP CSP 大概念 2 对齐。

If you are in…如果你在… Focus on these sections重点学习 Defer / lighter可推迟 / 减负 Source依据
🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP §1 through §7 in full. CSTA 3A-DA-10/11/12 cover data organisation, visualisation and models. AP CSP Big Idea 2 (DAT) topics 2.3 and 2.4 cover extracting information from data and using programs with data.§1 至 §7 完整学习。CSTA 3A-DA-10/11/12 涵盖数据组织、可视化和模型。AP CSP 大概念 2(DAT)主题 2.3 和 2.4 涵盖从数据中提取信息以及将程序与数据结合使用。 Nothing. AP CSP Big Idea 2 covers data, so all seven sections are core for AP students.无。AP CSP 大概念 2 围绕数据,所以七节对 AP 学生都是核心。 CSTA K-12 and AP CSP: CSTA 3A-DA-10, 3A-DA-11, 3A-DA-12; AP CSP Big Idea 2 (DAT) topics 2.3, 2.4:CSTA 3A-DA-10、3A-DA-11、3A-DA-12;AP CSP 大概念 2(DAT)主题 2.3、2.4
🇨🇦 ON: ICS4U (Grade 12 Univ.)安大略:ICS4U(12 年级大学预科) §1–§3 (data, file I/O, CSV) map directly to ICS4U A3.1. The file I/O worked examples in §2 practise the skill that A3.1 names. §6 (HTML) for context only.§1–§3(数据、文件读写、CSV)直接对应 ICS4U A3.1。§2 的文件读写例题练习 A3.1 所列的技能。§6(HTML)仅作背景。 §4–§5 (relational databases, SQL) are ICS4C college-stream content, so an ICS4U student can skip them.§4–§5(关系数据库、SQL)是 ICS4C 学院流内容,ICS4U 学生可以跳过。 ON/BC Computer Studies 11-12: ICS4U A3.1 (file I/O); ICS4C A2.2 (SQL):ICS4U A3.1(文件读写);ICS4C A2.2(SQL)
🇨🇦 BC: CIS 11 / CIS 12BC: CIS 11 / CIS 12 §1 (data vs information), §6 (HTML), §7 (JSON/APIs). CIS 11 covers Internet evolution; CIS 12 covers global shifts from online access. File I/O and SQL are enrichment for BC students.§1(数据与信息)、§6(HTML)、§7(JSON/接口)。CIS 11 涵盖互联网演变;CIS 12 涵盖在线访问带来的全球变革。文件读写和 SQL 对 BC 学生为拓展内容。 BC has no relational-database/SQL standard, so §4–§5 are enrichment.BC 没有关系数据库/SQL 标准,所以 §4–§5 为拓展内容。 ON/BC Computer Studies 11-12: BC CS10 big-data/IoT Content; CIS11/12 Internet/online Content bullets:BC CS10 大数据/物联网内容;CIS11/12 互联网/在线内容条目
🇨🇦 AB: CSE2130 / Web Pathway阿尔伯塔:CSE2130 / 网页路径 §1–§3 (data, file I/O) align with CSE2130 outcomes. §6 (HTML) maps to CSE1210/1220 client-side scripting. §7 (JSON/APIs) maps to CSE2210/3210.§1–§3(数据、文件读写)与 CSE2130 结果对齐。§6(HTML)对应 CSE1210/1220 客户端脚本。§7(JSON/接口)对应 CSE2210/3210。 §4–§5 (relational databases, SQL): no SQL module in the CSE cluster; treat as enrichment.§4–§5(关系数据库、SQL):CSE 群集中没有 SQL 模块;作为拓展内容。 Alberta CTS Computing Science: CSE2130 outcomes 1.4.2, 1.4.5, 1.4.6; CSE1210/1220 descriptions:CSE2130 结果 1.4.2、1.4.5、1.4.6;CSE1210/1220 描述

Once you have located your row, use the two cards below for the speed at which you should work through the recommended sections.找到所在行后,用下面两张卡片决定推进速度。

!
If you are cramming the night before如果你在临阵磨枪

Memorise three things: the difference between data and information; how to open, read, and write a file in Python; and what SELECT/WHERE does in SQL. Read every cram-cheat box. For AP CSP, know that Big Idea 2 covers how programs extract knowledge from data; JSON, CSV, and database queries are all examples.背熟三件事:数据与信息的区别;如何在 Python 中打开、读取和写入文件;SQL 中 SELECT/WHERE 的作用。读每个速记框。对于 AP CSP,要知道大概念 2 涵盖程序如何从数据中提取知识;JSON、CSV 和数据库查询都是例子。

*
If you are going for the top mark如果你目标顶分

Work through all seven sections in order. The sections build: data → files → CSV → relational tables → SQL → HTML → JSON/APIs. Each concept assumes the previous. For AP CSP, be able to write a program that reads a CSV, filters rows, and outputs a result; that is the synthesis of §2, §3, and §5 combined. For CSTA 3A-DA-11, be able to describe how you would visualise the data you just queried.按顺序学习全部七节。各节层层递进:数据 → 文件 → CSV → 关系表 → SQL → HTML → JSON/接口。每个概念都以前一个为基础。对于 AP CSP,能够编写读取 CSV、过滤行并输出结果的程序,这是 §2、§3 和 §5 的综合。对于 CSTA 3A-DA-11,能够描述如何可视化刚刚查询到的数据。