← 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详解

Control Flow · 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 Boolean Conditions布尔条件 · AP CSP 3.6 [3 marks][3 分]

Which Boolean expression evaluates to True when x = 7?x = 7 时,哪个布尔表达式的值为 True

Answer: (B) - x > 5 and x < 10答案:(B) - x > 5 and x < 10

Evaluate each option with x = 7: [1]x = 7 代入每个选项求值:[1]

(A) x == 67 == 6False. Incorrect.x == 67 == 6False。不正确。
(B) x > 5 and x < 107 > 5 is True AND 7 < 10 is TrueTrue and TrueTrue. Correct. [1]x > 5 and x < 107 > 5True7 < 10TrueTrue and TrueTrue。正确。[1]
(C) x != 77 != 7False. Incorrect.x != 77 != 7False。不正确。
(D) x > 10 or x < 37 > 10 is False OR 7 < 3 is FalseFalse or FalseFalse. Incorrect. [1]x > 10 or x < 37 > 10False7 < 3FalseFalse or FalseFalse。不正确。[1]
Insight:解题洞察: The and operator requires BOTH sub-conditions to be True simultaneously. Here, 7 lies strictly between 5 and 10, satisfying both halves. Option (D) is a common trap: or needs only one side True, but neither side is True for x = 7.and 运算符要求两个子条件同时为 True。这里 7 严格介于 5 和 10 之间,两个子条件均满足。选项 (D) 是常见陷阱:or 只需一边为 True,但 x = 7 时两边均为 False。
Q2 EASY 🇺🇸 US AP CSP-style MCQAP CSP 风格选择题 §2 if / elif / elseif / elif / else · AP CSP 3.6 [3 marks][3 分]

What does the following program output when score = 75?score = 75 时,以下程序输出什么?

if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
else:
    print("F")
Answer: (C) - output is C答案:(C) - 输出为 C

Trace the if/elif chain top to bottom with score = 75: [1]score = 75 从上到下追踪 if/elif 链:[1]

score >= 9075 >= 90 → False, skip. score >= 8075 >= 80 → False, skip. [1] score >= 7075 >= 70 → True, execute print("C"). The remaining branches are skipped. [1]score >= 9075 >= 90 → False,跳过。score >= 8075 >= 80 → False,跳过。[1] score >= 7075 >= 70 → True,执行 print("C"),其余分支跳过。[1]

Insight:解题洞察: In an if/elif/else chain, only the FIRST branch whose condition is True executes. Once one branch fires, Python skips all remaining branches. A score of 75 satisfies >= 70 but also technically satisfies lower thresholds, which do not matter here because the chain stops at the first match.在 if/elif/else 链中,只有第一个条件为 True 的分支会执行。一旦某个分支触发,Python 会跳过所有后续分支。75 满足 >= 70,但链式结构在首次匹配处停止,后续条件不再检查。
Q3 EASY 🇨🇦 ON ON Provincial-style安大略省考风格 §3 Nested Conditionals嵌套条件 · ICS3U A2.3 [4 marks][4 分]

Trace the nested conditional below with age = 15 and height = 130.age = 15height = 130 追踪以下嵌套条件。

IF age >= 12 THEN
    IF height >= 140 THEN
        OUTPUT "Welcome!"
    ELSE
        OUTPUT "Too short."
    END IF
ELSE
    OUTPUT "Too young."
END IF
Answer: "Too short."答案:"Too short."

Part (a) - Output [1]第 (a) 部分 - 输出 [1]

Output: Too short. [1]输出:Too short. [1]

Part (b) - Why the inner conditional executes [2]第 (b) 部分 - 内层条件为何被执行 [2]

The outer condition age >= 12 is checked first: 15 >= 12 is True, so execution enters the THEN block. [1] Inside that block, the inner condition height >= 140 is reached: 130 >= 140 is False, so the ELSE branch fires and outputs "Too short." [1]首先检查外层条件 age >= 1215 >= 12 为 True,故进入 THEN 块。[1] 在该块内,内层条件 height >= 140 被检查:130 >= 140 为 False,故执行 ELSE 分支,输出 "Too short."。[1]

Part (c) - Output if age = 10 [1]第 (c) 部分 - age = 10 时的输出 [1]

Output: Too young. - because 10 >= 12 is False so the outer ELSE fires and the inner conditional is never reached. [1]输出:Too young. - 因为 10 >= 12 为 False,外层 ELSE 分支触发,内层条件不会被执行到。[1]

Insight:解题洞察: In nested conditionals, the inner IF is only reachable if the outer IF condition is True. This creates a "guard" pattern: pass the first gate before the second is even checked. Here the age check guards the height check.在嵌套条件中,内层 IF 只有在外层 IF 条件为 True 时才可到达。这形成了"守卫"模式:只有通过第一道关卡,才会检查第二道。这里年龄检查保护了身高检查。
Q4 MEDIUM 🇨🇦 AB AB/Universal Applied阿省/通用应用题 §4 while Loopswhile 循环 · CSE1120 outcome 1 [7 marks][7 分]

Consider the pseudocode below.考察以下伪代码。

SET n TO 0
WHILE n < 5:
    SET n TO n + 2
OUTPUT n
Final output: 6最终输出:6

Part (a) - Trace table [3]第 (a) 部分 - 追踪表 [3]

Iteration迭代n before body循环体前 nCondition (n < 5)?条件(n < 5)?n after body循环体后 n
10True2
22True4
34True6

After iteration 3: n = 6. Check condition: 6 < 5 → False. Loop exits. [3]第 3 次迭代后:n = 6。检查条件:6 < 5 → False。循环退出。[3]

Part (b) - Final output [1]第 (b) 部分 - 最终输出 [1]

OUTPUT n prints 6. [1]OUTPUT n 打印 6[1]

Part (c) - Number of iterations [2]第 (c) 部分 - 循环次数 [2]

The loop body executes 3 times. [1] Justification: n starts at 0 and increments by 2 each time (0 → 2 → 4 → 6). The condition n < 5 is True for n = 0, 2, 4 and False for n = 6, giving exactly 3 iterations. [1]循环体执行 3 次。[1] 理由:n 从 0 开始,每次加 2(0 → 2 → 4 → 6)。条件 n < 5 在 n = 0, 2, 4 时为 True,n = 6 时为 False,恰好 3 次迭代。[1]

Part (d) - Condition for exactly 2 iterations [1]第 (d) 部分 - 使循环恰好执行 2 次的条件 [1]

Change the condition to n < 4. Then: iteration 1 (n=0, True, n becomes 2), iteration 2 (n=2, True, n becomes 4), check: 4 < 4 → False, exit. Exactly 2 iterations. [1]将条件改为 n < 4。则:第 1 次(n=0,True,n 变为 2),第 2 次(n=2,True,n 变为 4),检查:4 < 4 → False,退出。恰好 2 次。[1]

Insight:解题洞察: A while loop's condition is checked BEFORE each iteration, not after. This means if the condition is False from the start, the body never runs. The final value of n may overshoot the threshold (6 > 5 here) because the update happens inside the body before the next condition check.while 循环的条件在每次迭代前检查,而非之后。因此若初始条件即为 False,循环体永远不执行。n 的最终值可能超过阈值(此处 6 > 5),因为更新发生在循环体内,下次条件检查之前。
Q5 MEDIUM 🇨🇦 BC BC Provincial-style卑诗省考风格 §5 for Loopsfor 循环 · CSTA 3A-AP-15 [8 marks][8 分]

A student writes the following program to print multiples of 2 from 2 to 6 inclusive.一名学生编写以下程序,打印 2 到 6(含)的 2 的倍数。

for i in range(2, 8, 2):
    print(i)
Output: 2 / 4 / 6 (one per line)输出:2 / 4 / 6(每行一个)

Part (a) - Values of i [2]第 (a) 部分 - i 的取值 [2]

range(2, 8, 2) generates values starting at 2, stepping by 2, stopping before 8: 2, 4, 6. [2]range(2, 8, 2) 从 2 开始,步长 2,在 8 之前停止,生成:2, 4, 6[2]

Part (b) - Exact output [2]第 (b) 部分 - 精确输出 [2]

2
4
6

[2] (1 mark per correct line; all three required for full marks)[2](每行正确得 1 分;三行全对才能得满分)

Part (c) - Error in range(1, 10) and correction [2]第 (c) 部分 - range(1, 10) 的错误与纠正 [2]

Error: range(1, 10) stops before 10, so 10 is not included; the output would be 1 through 9 only. [1] Correction: use range(1, 11) so the stop value is 11, which causes Python to include 10. [1]错误:range(1, 10) 在 10 之前停止,因此 10 不被包含,输出仅为 1 到 9。[1] 纠正:改用 range(1, 11),停止值为 11,Python 因此会包含 10。[1]

Part (d) - When for is preferred over while [2]第 (d) 部分 - for 优于 while 的情形 [2]

A for loop is preferred when the number of iterations is known in advance (or when iterating over a defined sequence). [1] Example scenario: printing each student's name from a class list of 30 students; the count is fixed so for name in students: is cleaner than maintaining a counter in a while loop. [1]当迭代次数事先已知(或遍历已定义的序列)时,for 循环更合适。[1] 应用场景举例:打印 30 名学生名单中的每个名字,次数固定,for name in students: 比在 while 循环中维护计数器更简洁。[1]

Insight:解题洞察: range(start, stop, step): start is inclusive, stop is exclusive. The most common mistake is forgetting that the stop value is excluded, causing an off-by-one error. Always set stop = desired_last_value + 1 for inclusive counting.range(start, stop, step):start 含,stop 不含。最常见的错误是忘记 stop 值不被包含,导致差一错误。对于含端点计数,始终将 stop 设为所需最大值加一。
PART II  ·  EXTENDED RESPONSE  ·  SOLUTIONS第二部分  ·  简答题  ·  详解31 marks共 31 分
Q6 MEDIUM 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §6 break & continuebreak 与 continue · CSE1120 2.8 [8 marks][8 分]

Study the two programs below.研究以下两个程序。

numbers = [3, 7, 12, 5, 18]
for n in numbers:
    if n > 10:
        print("Found:", n)
        break
scores = [5, -3, 8, -1, 4]
total = 0
for s in scores:
    if s < 0:
        continue
    total += s
print(total)
Program A output: Found: 12  |  Program B output: 17程序 A 输出:Found: 12  |  程序 B 输出:17

Part (a) - Trace Program A [3]第 (a) 部分 - 追踪程序 A [3]

nn > 10?n > 10?Action操作
3Falsecontinue loop继续循环
7Falsecontinue loop继续循环
12Trueprint "Found: 12", break打印 "Found: 12",退出

Output: Found: 12. [1] The element that caused the loop to exit is 12 (first value > 10). [1] Elements 5 and 18 are never reached. [1]输出:Found: 12[1] 导致循环退出的元素是 12(第一个大于 10 的值)。[1] 元素 5 和 18 从未被访问到。[1]

Part (b) - Trace Program B step by step [3]第 (b) 部分 - 逐步追踪程序 B [3]

ss < 0?s < 0?Action操作total after迭代后 total
5Falsetotal += 5total += 55
-3Truecontinue (skip)continue(跳过)5
8Falsetotal += 8total += 813
-1Truecontinue (skip)continue(跳过)13
4Falsetotal += 4total += 417

Final output: 17. [3] (1 mark per correct row group; deduct 1 for each incorrect total value)最终输出:17[3](每组正确行得 1 分;total 值每错一处扣 1 分)

Part (c) - break vs continue [2]第 (c) 部分 - break 与 continue [2]

break immediately exits the entire loop, skipping all remaining iterations. [1] continue skips only the remainder of the current iteration and jumps to the next one, keeping the loop running. [1]break 立即退出整个循环,跳过所有剩余迭代。[1] continue 仅跳过当前迭代的剩余部分,直接进入下一次迭代,循环继续运行。[1]

Insight:解题洞察: Use break when you have found what you need and further searching is wasteful. Use continue when you want to filter out certain items but still process everything else. Program A searches for the first large number; Program B accumulates only non-negative values.当你找到所需结果、无需继续搜索时,使用 break。当你想过滤掉某些项目、但仍需处理其余项目时,使用 continue。程序 A 查找第一个较大的数;程序 B 只累加非负数。
Q7 MEDIUM 🇨🇦 ON ON Provincial-style安大略省考风格 §7 Nested Loops嵌套循环 · ICS3U A2.3 / CSE1120 2.8.2 [8 marks][8 分]

A program uses nested loops to find all pairs (i, j) where i and j are in [1, 3] and i + j == 4.一个程序用嵌套循环找到满足 i + j == 4 的所有整数对 (i, j),其中 i 和 j 均在 [1, 3] 内。

FOR i FROM 1 TO 3:
    FOR j FROM 1 TO 3:
        IF i + j == 4 THEN
            OUTPUT i, j
        END IF
    END FOR
END FOR
Pairs output: (1, 3), (2, 2), (3, 1)输出的对:(1, 3), (2, 2), (3, 1)

Part (a) - Total times inner body is checked [2]第 (a) 部分 - 内层循环体被检查的总次数 [2]

The outer loop runs for i = 1, 2, 3 (3 values). [1] For each value of i, the inner loop runs for j = 1, 2, 3 (3 values). Total checks = 3 x 3 = 9. [1]外层循环对 i = 1, 2, 3 运行(共 3 次)。[1] 每个 i 值对应内层循环对 j = 1, 2, 3 运行(共 3 次)。总检查次数 = 3 x 3 = 9[1]

Part (b) - All pairs satisfying i + j == 4 [3]第 (b) 部分 - 所有满足 i + j == 4 的对 [3]

iji + j== 4?== 4?Output?是否输出?
112No-
123No-
134Yes(1, 3)
213No-
224Yes(2, 2)
235No-
314Yes(3, 1)
325No-
336No-

Pairs output: (1, 3), (2, 2), (3, 1). [3] (1 mark per correct pair)输出的对:(1, 3)(2, 2)(3, 1)[3](每对正确得 1 分)

Part (c) - New outer loop for i from 1 to 5 [1]第 (c) 部分 - i 从 1 到 5 的新外层循环语句 [1]

FOR i FROM 1 TO 5 [1]FOR i FROM 1 TO 5 [1]

Part (d) - Why two separate counter variables are required [2]第 (d) 部分 - 为何需要两个独立计数器变量 [2]

Each counter tracks a different dimension of the iteration independently. [1] If both loops shared the same variable, advancing the inner loop would overwrite the outer loop's progress, making it impossible to enumerate all combinations of rows and columns correctly. [1]每个计数器独立跟踪迭代的一个维度。[1] 若两个循环共用同一个变量,内层循环的推进会覆盖外层循环的进度,导致无法正确枚举行列的所有组合。[1]

Insight:解题洞察: Nested loops create a Cartesian product of their iteration sequences. For m outer iterations and n inner iterations, the inner body runs exactly m x n times. This is the foundation of 2D grid traversal, matrix operations, and exhaustive pair-searching algorithms.嵌套循环创建其迭代序列的笛卡尔积。外层 m 次、内层 n 次,则内层循环体恰好运行 m x n 次。这是二维网格遍历、矩阵运算和穷举对搜索算法的基础。
Q8 HARD 🇨🇦 BC 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §2 + §4 if inside whilewhile 内嵌 if · CSTA 3A-AP-15 [8 marks][8 分]

A program accumulates a running total by repeatedly adding integers starting from 1. The loop stops as soon as the total exceeds 20.一个程序通过反复累加从 1 开始的整数来积累累计总和,当总和超过 20 时循环停止。

SET total TO 0
SET val TO 1
WHILE total <= 20:
    SET total TO total + val
    SET val TO val + 1
OUTPUT total
OUTPUT val
Outputs: total = 21, val = 7输出:total = 21,val = 7

Part (a) - Complete trace table [4]第 (a) 部分 - 完整追踪表 [4]

Iter迭代total after迭代后 totalval after迭代后 valtotal <= 20?total <= 20?
112True
233True
364True
4105True
5156True
6217False

[4] (1 mark per two correct rows; all six rows must be filled)[4](每两行正确得 1 分;六行须全部填写)

Part (b) - Two values output [2]第 (b) 部分 - 程序输出的两个值 [2]

OUTPUT total prints 21. [1] OUTPUT val prints 7. [1]OUTPUT total 打印 21[1] OUTPUT val 打印 7[1]

Part (c) - Modified condition to exceed 50 [1]第 (c) 部分 - 超过 50 的修改条件 [1]

Change WHILE total <= 20 to WHILE total <= 50. [1]WHILE total <= 20 改为 WHILE total <= 50[1]

Part (d) - Why while is more appropriate than for [1]第 (d) 部分 - while 比 for 更合适的原因 [1]

A while loop is more appropriate because the number of iterations is not known in advance; the loop continues until a data-dependent condition (total exceeding the threshold) is met, which cannot be expressed cleanly with a fixed range. [1]while 循环更合适,因为迭代次数事先不可知;循环持续运行直到满足与数据相关的条件(total 超过阈值),这无法用固定的 range 简洁表达。[1]

Insight:解题洞察: The total here is the sum of 1+2+3+4+5+6 = 21. This follows the triangular number pattern: the n-th triangular number is n(n+1)/2. The loop runs until the cumulative sum first exceeds 20, which happens at n = 6 (sum = 21). Recognising this pattern helps verify the trace without enumerating every step.这里的 total 是 1+2+3+4+5+6 = 21,遵循三角数规律:第 n 个三角数为 n(n+1)/2。循环运行到累计和首次超过 20,在 n = 6(sum = 21)时发生。识别此规律有助于不逐步枚举就验证追踪结果。
Q9 HARD Honors荣誉级 🇺🇸 US AP CSP-feeder FRQAP CSP 衔接简答题 §5 + §7 for + nested + analysisfor + 嵌套 + 分析 · CSTA 3A-AP-15 [7 marks][7 分]

A program prints a 2-row by 3-column grid of products.一个程序打印 2 行 3 列的乘积网格。

for row in range(1, 3):
    for col in range(1, 4):
        print(row * col, end=" ")
    print()
Output: 1 2 3  /  2 4 6 (two lines)输出:1 2 3  /  2 4 6(两行)

Part (a) - Complete output [3]第 (a) 部分 - 完整输出 [3]

row = 1: col = 1 prints 1 , col = 2 prints 2 , col = 3 prints 3 , then print() moves to next line. [1]row = 1:col = 1 打印 1 ,col = 2 打印 2 ,col = 3 打印 3 print() 换行。[1]

row = 2: col = 1 prints 2 , col = 2 prints 4 , col = 3 prints 6 , then print() moves to next line. [1]row = 2:col = 1 打印 2 ,col = 2 打印 4 ,col = 3 打印 6 print() 换行。[1]

1 2 3
2 4 6 

(Each number is followed by a space; print() adds a newline after each row.) [1](每个数字后跟一个空格;print() 在每行结束后换行。)[1]

Part (b) - Total executions of inner print [1]第 (b) 部分 - 内层 print 的总执行次数 [1]

print(row * col, end=" ") executes 2 (rows) x 3 (cols) = 6 times. [1]print(row * col, end=" ") 执行 2(行)x 3(列)= 6 次。[1]

Part (c) - Modified loop headers for 4 rows by 5 columns [2]第 (c) 部分 - 4 行 5 列的修改后循环头 [2]

for row in range(1, 5):
for col in range(1, 6):

[1] for the outer loop, [1] for the inner loop. (range stop = desired_last + 1)外层循环 [1],内层循环 [1]。(range 的 stop = 所需最大值 + 1)

Part (d) - Inner-body executions in terms of m and n [1]第 (d) 部分 - 用 m 和 n 表示内层循环体执行次数 [1]

Total inner-body executions = m x n. [1]内层循环体总执行次数 = m x n[1]

Insight:解题洞察: The end=" " argument suppresses the default newline and replaces it with a space, so all values in a row print on one line. The bare print() at the outer loop level then emits the newline that separates rows. This technique is the standard pattern for printing 2D grids in Python.end=" " 参数抑制了默认换行符,替换为空格,使同一行的所有值打印在一行上。外层循环级别的 print() 负责在行之间输出换行符。这是 Python 打印二维网格的标准技巧。
PART III  ·  MODELING / APPLIED  ·  SOLUTIONS第三部分  ·  建模与应用  ·  详解25 marks共 25 分
Q10 MEDIUM 🇺🇸 US 🇨🇦 ON AP CSP-feeder FRQAP CSP 衔接简答题 §4 + §5 Loop selection + accumulator循环选择 + 累加器 · ICS3U A2.2 [8 marks][8 分]

A program counts even numbers in a list and computes their sum.一个程序计算列表中偶数的个数,并计算它们的总和。

data = [3, 8, 5, 12, 7, 4, 11, 6]
count = 0
total = 0
for x in data:
    if x % 2 == 0:
        count += 1
        total += x
print(count)
print(total)
Outputs: count = 4, total = 30输出:count = 4,total = 30

Part (a) - Full trace [4]第 (a) 部分 - 完整追踪 [4]

xx % 2 == 0?countcounttotaltotal
3False00
8True18
5False18
12True220
7False220
4True324
11False324
6True430

[4] (1 mark per two correct rows; penalise cumulative total errors)[4](每两行正确得 1 分;累计 total 错误扣分)

Part (b) - Two values output [2]第 (b) 部分 - 两个输出值 [2]

print(count) outputs 4. [1] print(total) outputs 30. [1]print(count) 输出 4[1] print(total) 输出 30[1]

Part (c) - Why continue is not used; alternative version [2]第 (c) 部分 - 未使用 continue 的原因;使用 continue 的替代版本 [2]

The program uses an if block to only process even numbers; continue is not needed because the updates are already guarded inside the if body and odd numbers are simply skipped by not executing that block. [1]程序使用 if 块来只处理偶数;不需要 continue,因为更新操作已在 if 体内受到保护,奇数只需不执行该块即可跳过。[1]

Alternative version using continue: [1]使用 continue 的替代版本:[1]

FOR x IN data:
    IF x % 2 != 0 THEN
        CONTINUE
    END IF
    count += 1
    total += x
Insight:解题洞察: The accumulator pattern (initialise counter/total to 0, update inside the loop) is one of the most fundamental algorithmic building blocks. The even numbers in data are 8, 12, 4, 6; their sum is 8 + 12 + 4 + 6 = 30. Spotting them before tracing lets you verify the trace quickly.累加器模式(将 counter/total 初始化为 0,在循环内更新)是最基本的算法构件之一。data 中的偶数为 8、12、4、6;它们的和为 8 + 12 + 4 + 6 = 30。追踪前先识别它们可以快速验证结果。
Q11 MEDIUM 🇨🇦 ON 🇨🇦 BC ON Provincial-style安大略省考风格 §2 + §3 + §5 Design: conditionals + for设计:条件 + for · ICS3U A2.2 [9 marks][9 分]

A student designs a program to print even numbers from 10 down to 2 using a while loop with an if inside.一名学生设计一个程序,使用 while 循环加内嵌 if 按降序打印 10 到 2 的偶数。

SET i TO 10
WHILE i >= 2:
    IF i % 2 == 0 THEN
        OUTPUT i
    END IF
    SET i TO i - 1
END WHILE
Output: 10, 8, 6, 4, 2 (one per line)输出:10, 8, 6, 4, 2(每行一个)

Part (a) - Complete output [3]第 (a) 部分 - 完整输出 [3]

Trace: i starts at 10. Each iteration checks if i is even and outputs it, then decrements. Even values encountered: 10, 8, 6, 4, 2. When i = 1: 1 >= 2 is False, loop exits. [3] (1 mark per correct output line up to 3)追踪:i 从 10 开始,每次迭代检查 i 是否为偶数并输出,然后递减。遇到的偶数:10、8、6、4、2。当 i = 1 时:1 >= 2 为 False,循环退出。[3](每行正确输出得 1 分,最多 3 分)

10
8
6
4
2

Part (b) - Total loop body executions and OUTPUT executions [2]第 (b) 部分 - 循环体总执行次数与 OUTPUT 执行次数 [2]

The loop body executes 9 times (i = 10, 9, 8, 7, 6, 5, 4, 3, 2). [1] The OUTPUT statement executes 5 times (for even values: 10, 8, 6, 4, 2). [1]循环体执行 9 次(i = 10, 9, 8, 7, 6, 5, 4, 3, 2)。[1] OUTPUT 语句执行 5 次(对应偶数:10、8、6、4、2)。[1]

Part (c) - Rewrite using for with range, no if needed [3]第 (c) 部分 - 用带 range 的 for 循环改写,无需 if [3]

for i in range(10, 1, -2):
    print(i)

[3]: 1 mark for range with correct start (10), 1 mark for correct stop (1, so 2 is included), 1 mark for correct step (-2). Accept any valid equivalent.[3]:start 正确(10)得 1 分,stop 正确(1,使 2 被包含)得 1 分,step 正确(-2)得 1 分。接受任何等效的正确写法。

Part (d) - One advantage of the for version [1]第 (d) 部分 - for 版本的一个优点 [1]

The for version is shorter and eliminates both the explicit counter decrement and the if statement, reducing the risk of errors such as forgetting to update the counter. [1]for 版本更简洁,省去了显式计数器递减和 if 语句,降低了忘记更新计数器等错误的风险。[1]

Insight:解题洞察: range(start, stop, step) supports negative steps for countdown loops. range(10, 1, -2) produces 10, 8, 6, 4, 2 directly, eliminating the need for a separate parity check. When the step encodes the selection logic, the if statement inside the loop becomes redundant.range(start, stop, step) 支持负步长用于倒计时循环。range(10, 1, -2) 直接生成 10, 8, 6, 4, 2,无需单独的奇偶检查。当步长本身已编码了选择逻辑时,循环内的 if 语句就变得多余了。
Q12 HARD 🇺🇸 US 🇨🇦 ON 🇨🇦 BC AP CSP-feeder FRQAP CSP 衔接简答题 All sections · Debugging + extension全节综合 · 调试与扩展 · CSTA 3A-AP-15 [8 marks][8 分]

A program finds and prints the first value in a list greater than a threshold, then stops.一个程序查找并打印列表中第一个大于给定阈值的值,然后停止。

data = [4, 9, 2, 15, 7]
threshold = 10
for i in range(len(data)):
    if data[i] > threshold:
        print("Found at index", i, ":", data[i])
        break
Output: Found at index 3 : 15输出:Found at index 3 : 15

Part (a) - Step-by-step loop trace [3]第 (a) 部分 - 逐步循环追踪 [3]

idata[i]data[i] > 10?data[i] > 10?Action操作
04Falsecontinue loop继续循环
19Falsecontinue loop继续循环
22Falsecontinue loop继续循环
315Trueprint output, break打印输出,退出

[3] (1 mark per column correct across all rows; i=4 never reached due to break)[3](各列全行正确得 1 分;由于 break,i=4 从未被访问)

Part (b) - Program output [1]第 (b) 部分 - 程序输出 [1]

Found at index 3 : 15 [1]Found at index 3 : 15 [1]

Part (c) - Behaviour without break; all values now printed [2]第 (c) 部分 - 删去 break 后的行为;现在打印的所有值 [2]

Without break, the loop continues checking all remaining elements after finding 15 at index 3. [1] The loop then checks index 4: data[4] = 7, 7 > 10 is False, so nothing additional is printed. The only value printed is still Found at index 3 : 15 because 7 does not exceed the threshold. The program no longer stops early and completes the full iteration. [1]删去 break 后,循环在找到索引 3 处的 15 之后继续检查剩余元素。[1] 接着检查索引 4:data[4] = 77 > 10 为 False,不打印额外内容。唯一打印的仍是 Found at index 3 : 15,因为 7 不超过阈值。程序不再提前停止,完成全部迭代。[1]

Part (d) - Extension: print "Not found" if no value exceeds threshold [2]第 (d) 部分 - 扩展:若无值超过阈值则打印 "Not found" [2]

found = False
for i in range(len(data)):
    if data[i] > threshold:
        print("Found at index", i, ":", data[i])
        found = True
        break
if not found:
    print("Not found")

[1] for the found flag initialised before the loop, [1] for the correct post-loop check. (Accept equivalent pseudocode.)[1] 用于在循环前初始化 found 标志,[1] 用于循环后的正确检查。(接受等效的伪代码。)

Insight:解题洞察: The "search with a flag" pattern is fundamental to linear search algorithms. Setting a boolean flag before the loop and checking it after is the standard way to detect whether a loop found what it was looking for. Python also supports an elegant for/else construct where the else block runs only when the loop completes without hitting a break, achieving the same result more concisely."带标志搜索"模式是线性搜索算法的基础。在循环前设置布尔标志并在循环后检查是检测循环是否找到所需内容的标准方式。Python 还支持优雅的 for/else 结构,else 块仅在循环未触发 break 的情况下执行,以更简洁的方式实现相同效果。