High School Computer Science

Control Flow控制流程

Control flow is how a program decides which statements to execute and how many times to repeat them. Instead of running every line top-to-bottom exactly once, a program can branch on a boolean condition (if / elif / else), repeat a block while a condition holds (while), or iterate over a fixed sequence (for). This guide builds each construct from scratch: boolean expressions and comparison operators, selection with if/elif/else, nested conditionals, while loops, for loops, loop control with break and continue, and nested loops. Every concept is shown in pseudocode then in Python, with ZH explanations after each code block.控制流程(control flow,控制流程)决定程序执行哪些语句、重复多少次。程序不再从上到下逐行各执行一次,而是可以根据布尔条件(boolean condition,布尔条件)分支(if / elif / else,条件选择),或在条件成立时重复执行代码块(while,当型循环),或遍历固定序列(for,计数循环)。本指南逐一构建每个结构:布尔表达式与比较运算符、if/elif/else 选择、嵌套条件(nested conditionals,嵌套条件)、while 循环(loop,循环)、for 循环、break 与 continue 循环控制,以及嵌套循环(nested loops,嵌套循环)。全部概念均先用伪代码展示,再给出 Python 实现,代码块后附中文说明。

7 sections7 节内容 US CSTA · AP CSP · ON · BC · ABUS CSTA · AP CSP · ON · BC · AB Pseudocode + Python worked examples伪代码 + Python 例题

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

Control flow is assessed in every curriculum we map to. All four agree on the core constructs: boolean conditions, selection (if/elif/else), and iteration (while, for). Where they diverge is on nesting depth and loop-control keywords: Alberta CSE1120 explicitly names nested conditional and nested iterative blocks; AP CSP limits to what can be expressed in its reference-sheet pseudocode. The table below tells you which sections are core for you. Every section uses pseudocode first, then Python.控制流程在我们对照的所有大纲中均为考核内容。四套大纲对核心构造高度一致:布尔条件(boolean,布尔)、选择(selection,选择)和迭代(iteration,迭代)。它们的分歧在于嵌套深度和循环控制关键字:阿尔伯塔 CSE1120 明确点名嵌套条件块和嵌套迭代块;AP CSP 限于其参考手册伪代码所能表达的内容。下表告诉你哪些节属于你的核心。所有节均先用伪代码,再用 Python。

If you are in…如果你在… Focus on these sections重点学习 Defer / lighter可推迟 / 减负 Source依据
🇺🇸 US CSTA / AP CSP美国 CSTA / AP CSP §1–§5 core (booleans, if/elif/else, nested conditionals, while, for). CSTA 3A-AP-15 and AP CSP topics 3.5–3.8 all map here.§1–§5 为核心(布尔、if/elif/else、嵌套条件、while、for)。CSTA 3A-AP-15 和 AP CSP 主题 3.5–3.8 均对应此处。 §6 break/continue — AP CSP pseudocode does not include break/continue keywords; treat as enrichment.§6 break/continue — AP CSP 伪代码不含 break/continue 关键字;作为拓展内容。 CSTA K-12 and AP CSP — CSTA 3A-AP-15; AP CSP Big Idea 3 (AAP) topics 3.5, 3.6, 3.7, 3.8— CSTA 3A-AP-15;AP CSP 大概念 3 主题 3.5、3.6、3.7、3.8
🇨🇦 ON Grade 11 — ICS3U安大略 11 年级 — ICS3U §1–§7 in full. ICS3U A2.2 (sequence, selection, repetition) and A2.3 (nested structures) map directly to every section.§1–§7 完整学习。ICS3U A2.2(顺序、选择、重复)和 A2.3(嵌套结构)直接对应每一节。 Nothing to defer — all seven sections are core ICS3U A2 content.无可推迟——全部七节均为 ICS3U A2 核心内容。 ON/BC Computer Studies 11-12 — ICS3U Strand A A2, A2.2, A2.3— ICS3U A 单元 A2、A2.2、A2.3
🇨🇦 BC — CS10 / CP11BC — CS10 / CP11 §1–§7. BC CS10 names "decision structure for two or more choices" and "looping structures" verbatim. CP11 names "logic, decision structure, and loops."§1–§7。BC CS10 原文命名"两个或多个选择的判断结构"和"循环结构"。CP11 命名"逻辑、判断结构和循环"。 BC has no explicit break/continue standard; §6 is enrichment.BC 无明确的 break/continue 标准;§6 为拓展内容。 ON/BC Computer Studies 11-12 — BC CS10 decision/loop Content; CP11 "logic, decision structure, and loops" Content— BC CS10 判断/循环内容;CP11"逻辑、判断结构和循环"内容
🇨🇦 AB — CSE1120阿尔伯塔 — CSE1120 §1–§7 in full. CSE1120 outcome 1 names selection and iteration explicitly; outcome 2.8 names nested conditionals and nested iterative blocks.§1–§7 完整学习。CSE1120 结果 1 明确命名选择和迭代;结果 2.8 命名嵌套条件块和嵌套迭代块。 Nothing to defer — CSE1120 covers all seven topics at the Introductory level.无可推迟——CSE1120 在入门级覆盖全部七个主题。 Alberta CTS Computing Science — CSE1120 outcomes 1, 2.6, 2.8, 2.8.1, 2.8.2— CSE1120 结果 1、2.6、2.8、2.8.1、2.8.2
!
If you are cramming the night before如果你在临阵磨枪

Memorise three things: how to write a boolean condition with comparison operators; the if/elif/else template; and the difference between while (condition-controlled) and for (count-controlled). Read every cram-cheat box. Trace the pseudocode examples with a concrete value before moving on.背熟三件事:如何用比较运算符写布尔条件(boolean condition,布尔条件);if/elif/else 模板;以及 while(条件控制)和 for(计数控制)的区别。读每个速记框。在继续之前用具体值追踪伪代码示例。

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

For every loop or conditional you write, ask: which construct fits best and why? CSTA 3A-AP-15 requires you to justify your choice of control structure in terms of readability and performance. Trace every loop example with a variable table. Master nested structures (§3 and §7) — they appear on every exam.对于你编写的每个循环(loop,循环)或条件语句,问自己:哪种结构最合适,为什么?CSTA 3A-AP-15 要求你从可读性和性能角度论证控制结构的选择。用变量表追踪每个循环示例。掌握嵌套结构(nested,嵌套)(§3 和 §7)——它们出现在每次考试中。


Boolean Conditions & Comparison布尔条件与比较

Six comparison operators — memorise these.六个比较运算符 — 背熟这些。
  • == equal to   等于   != not equal to不等于
  • < less than   小于   > greater than大于
  • <= less than or equal   小于等于   >= greater than or equal大于等于
Boolean expressions evaluate to True or False. Combine with and, or, not. Key trap: x = 5 assigns; x == 5 tests. CSE1120 outcome 2.6 names "relational, Boolean" operators explicitly.布尔表达式boolean expression,布尔表达式)求值为 TrueFalse。用 and(与)、or(或)、not(非)组合。关键陷阱:x = 5 是赋值;x == 5 是测试。CSE1120 结果 2.6 明确命名"关系、布尔"运算符。
B
Worked Example 1 · Boolean expressions in pseudocode and Python例题 1 · 伪代码与 Python 中的布尔表达式
SET age TO 17
SET has_ticket TO True
IF age >= 18 AND has_ticket THEN
    OUTPUT "Admitted"
ELSE
    OUTPUT "Not admitted"
END IF

SET age TO 17 assigns 17 to age; age >= 18 tests whether age is at least 18 (a Boolean condition); AND requires both conditions to be true.SET age TO 17 将 age 设为 17(赋值);age >= 18 测试是否大于等于 18(布尔条件);AND 要求两个条件同时为真。

age = 17
has_ticket = True
if age >= 18 and has_ticket:
    print("Admitted")
else:
    print("Not admitted")   # outputs: Not admitted

In Python, Boolean keywords are lowercase: and, or, not, True, False.Python 布尔关键字小写:and(与)、or(或)、not(非)、True(真)、False(假)。

Which expression evaluates to True when x = 4?x = 4 时,哪个表达式的值为 True
§1 · Q1
x == 5
x > 4
x >= 4
x != 4
x >= 4 is True when x equals 4 (4 ≥ 4). The other three: x==5 is False (4≠5); x>4 is False (4 is not strictly greater than 4); x!=4 is False (4 equals 4).x >= 4 当 x 等于 4 时为 True(4 ≥ 4)。其余三个:x==5 为 False(4≠5);x>4 为 False(4 不严格大于 4);x!=4 为 False(4 等于 4)。
With x=4: x==5 is False; x>4 is False (strict greater-than); x!=4 is False; only x>=4 is True.x=4 时:x==5 为 False;x>4 为 False(严格大于);x!=4 为 False;只有 x>=4 为 True。
What does not (x > 3) equal when x = 5?x = 5 时,not (x > 3) 等于什么?
§1 · Q2
True
False
5
Error错误
x>3 is True (5>3). not True = False.x>3 为 True(5>3)。not True = False。
Step 1: x>3 = True. Step 2: not True = False.第 1 步:x>3 = True。第 2 步:not True = False。

if / elif / elseif / elif / else

The template — memorise the skeleton.模板 — 背熟骨架。
IF condition THEN
    statements
ELIF other_condition THEN
    statements
ELSE
    statements
END IF
Only one branch executes. elif (else-if) adds more conditions; else is the catch-all fallback. ICS3U A2.2 calls this "selection control structure." CSE1120 outcome 1 names "selection (decision making)." AP CSP topic 3.6 is Conditionals; 3.7 is Nested Conditionals.只有一个分支(branch,分支)执行。elif(否则如果)增加更多条件(condition,条件);else(否则)是兜底回退。ICS3U A2.2 称之为"选择控制结构"。CSE1120 结果 1 命名"选择(决策)"。AP CSP 主题 3.6 为条件语句;3.7 为嵌套条件。
WE
Worked Example 2 · Letter grade classifier例题 2 · 字母等级分类

Problem: given a numeric score (0–100), output the letter grade (A, B, C, D, F).问题:给定数字成绩(0–100),输出字母等级(A、B、C、D、F)。

INPUT score
IF score >= 90 THEN
    OUTPUT "A"
ELIF score >= 80 THEN
    OUTPUT "B"
ELIF score >= 70 THEN
    OUTPUT "C"
ELIF score >= 60 THEN
    OUTPUT "D"
ELSE
    OUTPUT "F"
END IF

Conditions are ordered from highest to lowest; once one ELIF is true, the remaining branches are skipped.条件(condition,条件)从高到低排列;一旦某个 ELIF(否则如果)为真,其余分支跳过。

score = int(input())
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

Python's elif is short for "else if". A colon : ends the condition line; indentation marks the code block.Python 的 elif 是 "else if" 的缩写。冒号 : 结束条件行,缩进(indentation,缩进)标记代码块。

For score = 75 in the grade classifier above, which branch executes?在上面的等级分类中,score = 75 时哪个分支执行?
§2 · Q1
The if score >= 90 branch (outputs A)if score >= 90 分支(输出 A)
The elif score >= 80 branch (outputs B)elif score >= 80 分支(输出 B)
The elif score >= 70 branch (outputs C)elif score >= 70 分支(输出 C)
The else branch (outputs F)else 分支(输出 F)
75>=90? No. 75>=80? No. 75>=70? Yes → outputs C. Python evaluates conditions top-to-bottom and stops at the first True branch.75>=90?否。75>=80?否。75>=70?是 → 输出 C。Python 从上到下依次评估条件,在第一个为真的分支停止。
75>=90 is False; 75>=80 is False; 75>=70 is True → C branch.75>=90 为 False;75>=80 为 False;75>=70 为 True → C 分支。
What is the output of this pseudocode with x = 10?
IF x > 5 THEN OUTPUT "big" ELSE OUTPUT "small" END IF
以下伪代码在 x = 10 时的输出是什么?
IF x > 5 THEN OUTPUT "big" ELSE OUTPUT "small" END IF
§2 · Q2
big
small
Both "big" and "small""big" 和 "small" 都输出
Nothing什么都不输出
10 > 5 is True → the IF branch executes: outputs "big". The ELSE branch is skipped.10 > 5 为 True → IF 分支执行:输出 "big"。ELSE 分支跳过。
Only one branch executes. 10>5 is True, so "big" runs; "small" is skipped.只有一个分支执行。10>5 为 True,所以 "big" 运行;"small" 被跳过。

Nested Conditionals嵌套条件

A nested conditional is an if/elif/else inside another if/elif/else.嵌套条件(nested conditional,嵌套条件)是一个 if/elif/else 嵌套在另一个 if/elif/else 内部。
  • The inner block only runs if the outer condition is True.只有外层条件为真时,内层代码块才运行。
  • Indentation reveals the nesting structure — each level adds one indent in Python.缩进(indentation,缩进)揭示嵌套结构 — Python 中每一层多一级缩进。
  • CSE1120 outcome 2.8.1 names "nested conditional blocks" explicitly. ICS3U A2.3 requires "nested structures."CSE1120 结果 2.8.1 明确命名"嵌套条件块"。ICS3U A2.3 要求"嵌套结构"。
Key trap: deep nesting makes code hard to read. If you have more than two levels, consider using elif or combining conditions with and/or. CSTA 3A-AP-15 asks you to justify control-structure choices for readability.关键陷阱:深层嵌套使代码难以阅读。如果超过两层,考虑使用 elif(否则如果)或用 and/or 合并条件。CSTA 3A-AP-15 要求你从可读性角度论证控制结构选择。
WE
Worked Example 3 · Theme-park entry check例题 3 · 主题乐园入场检查

Problem: a rider must be at least 12 years old AND at least 140 cm tall. If under 12, output "Too young." If at least 12 but under 140 cm, output "Too short." Otherwise output "Enjoy the ride!"问题:乘客必须至少 12 岁且身高至少 140 厘米。若未满 12 岁,输出"年龄不足";若满 12 岁但身高不足 140 厘米,输出"身高不足";否则输出"请享受!"

INPUT age, height
IF age >= 12 THEN
    IF height >= 140 THEN
        OUTPUT "Enjoy the ride!"
    ELSE
        OUTPUT "Too short."
    END IF
ELSE
    OUTPUT "Too young."
END IF

The outer IF checks age first; only if age qualifies does the inner IF check height. The two END IF statements close the inner and outer blocks respectively.外层 IF 先检查年龄(age,年龄);只有年龄合格,内层 IF 才检查身高(height,身高)。两个 END IF 分别关闭内外两层。

age = int(input())
height = int(input())
if age >= 12:
    if height >= 140:
        print("Enjoy the ride!")
    else:
        print("Too short.")
else:
    print("Too young.")

Python uses indentation to show nesting level. The inner if/else is indented an additional 4 spaces relative to the outer block.Python 用缩进(indentation,缩进)表示嵌套层级——内层 if/else 多缩进 4 个空格。

In the theme-park example, what is the output when age = 10 and height = 150?在主题乐园例题中,当 age = 10height = 150 时,输出是什么?
§3 · Q1
Enjoy the ride!请享受!
Too short.身高不足。
Both messages两条消息都输出
Too young.年龄不足。
age=10 < 12 → outer IF is False → ELSE branch: "Too young." The inner height check is never reached.age=10 < 12 → 外层 IF 为 False → ELSE 分支:"年龄不足。" 内层身高检查不会执行。
The outer condition (age >= 12) fails first. The inner if never runs.外层条件(age >= 12)先失败。内层 if 不执行。

while Loopswhile 循环

while = repeat while condition is True; stops the moment condition becomes False.while = 在条件为 True 时重复;条件变为 False 时立即停止。
WHILE condition:
    body statements
END WHILE
The condition is checked before each iteration. If it is False on entry, the body never runs. Key trap: you must update a variable inside the body that eventually makes the condition False; otherwise you get an infinite loop. ICS3U A2.2 calls this "repetition control structure." CSE1120 outcome 1 names "iteration (repetition)."条件在每次迭代(iteration,迭代)之前检查。若入口时为 False,循环体一次都不执行。关键陷阱:必须在循环体内更新某个变量,使条件最终变为 False;否则会产生无限循环(infinite loop,无限循环)。ICS3U A2.2 称之为"重复控制结构";CSE1120 结果 1 命名"迭代(重复)"。
WE
Worked Example 4 · Countdown with while例题 4 · 用 while 实现倒计时

Print: 5 4 3 2 1 Blast off!打印:5 4 3 2 1 发射!

SET count TO 5
WHILE count >= 1:
    OUTPUT count
    SET count TO count - 1
OUTPUT "Blast off!"

count starts at 5; each iteration outputs count then decrements it by 1; when count reaches 0, count >= 1 is False and the loop ends.count 开始为 5;每次循环输出 count,然后减 1;当 count 变为 0 时,count >= 1 为 False,循环(loop,循环)结束。

count = 5
while count >= 1:
    print(count)
    count -= 1
print("Blast off!")

Python's count -= 1 is shorthand for count = count - 1 (the subtraction assignment operator).Python count -= 1count = count - 1 的简写(减法赋值运算符)。

How many times does the body of this loop execute?
SET x TO 1
WHILE x < 4: SET x TO x + 1
这个循环的循环体执行多少次?
SET x TO 1
WHILE x < 4: SET x TO x + 1
§4 · Q1
2
3
4
Infinite (never stops)无限(永不停止)
Trace: x=1 (1<4 True, x→2), x=2 (2<4 True, x→3), x=3 (3<4 True, x→4), x=4 (4<4 False, exits). Body ran 3 times.追踪:x=1(1<4 True,x→2),x=2(2<4 True,x→3),x=3(3<4 True,x→4),x=4(4<4 False,退出)。循环体运行 3 次。
x goes 1, 2, 3, 4. At x=4 the condition 4<4 is False and the loop exits — 3 iterations.x 经历 1、2、3、4。当 x=4 时条件 4<4 为 False,循环退出——3 次迭代。
What happens if a while loop's condition never becomes False?如果 while 循环的条件永远不变为 False,会发生什么?
§4 · Q2
The loop runs exactly once循环恰好运行一次
A syntax error is raised引发语法错误
An infinite loop — the program runs forever (or until forced to stop)无限循环——程序永远运行(或直到被强制停止)
The loop skips its body循环跳过其循环体
An infinite loop occurs when the condition is always True. The program never exits the loop body. Common cause: forgetting to update the variable that the condition depends on.当条件始终为 True 时会发生无限循环(infinite loop,无限循环)。程序永远不会退出循环体。常见原因:忘记更新条件所依赖的变量。
If the condition never becomes False, the loop body repeats indefinitely — an infinite loop. This is a logic error, not a syntax error.如果条件永远不变为 False,循环体无限重复——无限循环。这是逻辑错误,不是语法错误。

for Loopsfor 循环

for = iterate over a known sequence (list, range). The loop variable takes each value in turn.for = 遍历已知序列(列表、范围)。循环变量(loop variable,循环变量)依次取每个值。
FOR item IN collection:
    body statements
END FOR
Use for when you know the number of iterations in advance (or are iterating a collection). Use while when you repeat until a condition changes. Python's range(start, stop) generates integers from start up to (but not including) stop. CSTA 3A-AP-15 asks you to justify choosing for vs while for readability.当你提前知道迭代次数(或在遍历集合)时使用 for。当你在条件改变前重复时使用 while。Python 的 range(start, stop) 生成从 start 到(不包含)stop 的整数。CSTA 3A-AP-15 要求你从可读性角度论证选择 for 还是 while。
WE
Worked Example 5 · Sum of 1 to n with for例题 5 · 用 for 求 1 到 n 的和

Read n from input. Output the sum 1 + 2 + … + n.从输入读取 n。输出 1 + 2 + … + n 的和。

INPUT n
SET total TO 0
FOR i FROM 1 TO n:
    SET total TO total + i
OUTPUT total

i takes values from 1 through n (inclusive); each iteration adds i to total; after the loop, total is output.i 从 1 取到 n(含 n);每次将 i 累加到 total;结束后输出 total。

n = int(input())
total = 0
for i in range(1, n + 1):   # range(1, n+1) gives 1, 2, ..., n
    total += i
print(total)

Python's range(1, n+1) generates 1, 2, ..., n. The stop value is excluded, so n+1 is needed to include n.Python range(1, n+1) 生成 1, 2, …, n。注意 stop 值不含在内,所以需写 n+1(差一陷阱)。

What does for i in range(3, 7) print when you print i each iteration?for i in range(3, 7) 每次迭代打印 i,会打印什么?
§5 · Q1
3 4 5 6 7
3 4 5
4 5 6 7
3 4 5 6
range(3, 7) generates 3, 4, 5, 6. Stop value 7 is excluded. This is the standard Python range: [start, stop).range(3, 7) 生成 3, 4, 5, 6。stop 值 7 不包含在内。这是标准的 Python range:[start, stop)。
range(start, stop) goes from start up to but NOT including stop. range(3,7) = 3,4,5,6.range(start, stop) 从 start 到 stop(不含 stop)。range(3,7) = 3,4,5,6。
Which loop type is best when you need to repeat until a user types "quit" (unknown number of iterations)?当你需要重复直到用户输入"quit"(未知迭代次数)时,哪种循环最合适?
§5 · Q2
while loop — condition-controlled, runs until a condition changeswhile 循环——条件控制,运行直到条件改变
for loop — count-controlled, iterates a fixed number of timesfor 循环——计数控制,迭代固定次数
if/elif — selection, not a loopif/elif——选择,不是循环
Either loop works identically here两种循环在这里完全相同
When the number of repetitions is unknown and depends on a condition (user typing "quit"), while is the natural choice. CSTA 3A-AP-15 asks you to justify this kind of choice.当重复次数未知且取决于条件(用户输入"quit")时,while 是自然选择。CSTA 3A-AP-15 要求你论证这种选择。
for is best for known-count iterations; while is best when the count depends on a condition. "Until the user types quit" is condition-controlled → while.for 最适合已知次数的迭代;while 最适合次数取决于条件的情况。"直到用户输入 quit"是条件控制 → while。

Loop Control: break & continue循环控制:break 与 continue

Two loop-control keywords — use sparingly, always comment why.两个循环控制关键字 — 谨慎使用,始终注释原因。
  • break — immediately exits the innermost loop. The program continues after the loop. Use when you have found what you need and further iteration is wasted work.— 立即退出最内层循环(break,中断)。程序在循环后继续。当你找到所需内容且进一步迭代是浪费时使用。
  • continue — skips the rest of the current iteration and jumps back to the loop's condition check. Use to skip items that do not meet a filter.— 跳过当前迭代的剩余部分,跳回循环条件检查(continue,继续)。用于跳过不满足过滤条件的项目。
CSE1120 outcome 2.8 says "use appropriate selection and iteration structures to avoid unconditional branching or exiting from the interior of a block" — break/continue should be deliberate and documented. AP CSP pseudocode does not include break/continue; treat this section as enrichment for AP CSP students.CSE1120 结果 2.8 要求"使用适当的选择和迭代结构以避免无条件分支或从块内部退出"——break/continue 应谨慎使用并加以注释(comment,注释)。AP CSP 伪代码不包含 break/continue;AP CSP 学生将此节作为拓展内容。
WE
Worked Example 6 · Search with break; skip negatives with continue例题 6 · 用 break 搜索;用 continue 跳过负数

break — find first even number.break — 找第一个偶数。

numbers = [3, 7, 12, 5, 8]
for n in numbers:
    if n % 2 == 0:
        print("First even:", n)
        break   # stop as soon as found

n % 2 == 0 tests whether n is even; once the condition is true, the value is printed and break exits the loop without checking the remaining elements. Output: First even: 12.n % 2 == 0 测试 n 是否为偶数;一旦条件为真,打印并 break(中断)退出循环,不再检查后续元素。输出:First even: 12

continue — print only positive numbers.continue — 只打印正数。

scores = [85, -1, 92, -5, 78]
for s in scores:
    if s < 0:
        continue   # skip invalid (negative) scores
    print(s)

When s < 0, continue skips print(s) and jumps directly to the next iteration. Output: 85, 92, 78.当 s < 0 时,continue(继续)跳过 print(s),直接进入下一次迭代(iteration,迭代)。输出:85, 92, 78。

What does break do when executed inside a loop?break 在循环内部执行时会做什么?
§6 · Q1
Exits the innermost loop immediately立即退出最内层循环
Skips the rest of the current iteration and goes to the next跳过当前迭代的剩余部分,进入下一次迭代
Restarts the loop from the beginning从头重新开始循环
Ends the entire program结束整个程序
break exits the innermost loop immediately. Execution continues with the first statement after the loop. It does not end the program or restart the loop.break(中断)立即退出最内层循环。执行继续循环后的第一条语句。它不会结束程序或重新开始循环。
break = exit loop. continue = skip to next iteration. break does not restart or end the program.break = 退出循环。continue = 跳到下一次迭代。break 不会重新开始或结束程序。
What does continue do when executed inside a loop?continue 在循环内部执行时会做什么?
§6 · Q2
Exits the loop退出循环
Skips the remaining statements in the current iteration and goes back to the loop condition跳过当前迭代的剩余语句,返回循环条件
Starts the loop over from the first iteration从第一次迭代重新开始循环
Prints a blank line打印空行
continue skips the remaining body statements and jumps back to the loop's condition check (for while) or next item (for for). It does not exit the loop.continue(继续)跳过剩余的循环体语句,跳回循环条件检查(while 循环)或下一个项目(for 循环)。它不会退出循环。
continue does not exit — that is break. continue skips the rest of the current pass and moves to the next iteration.continue 不退出——那是 break。continue 跳过当前轮次的剩余部分,移动到下一次迭代。

Nested Loops嵌套循环

A nested loop is a loop inside another loop. The inner loop runs completely for every single iteration of the outer loop.嵌套循环(nested loop,嵌套循环)是一个循环在另一个循环内部。内层循环在外层循环的每一次迭代中完整运行一遍。
  • Total iterations = outer count × inner count. For outer=3, inner=4: 12 total body executions.总迭代次数 = 外层次数 × 内层次数。外层=3,内层=4:共 12 次循环体执行。
  • Classic use: processing a grid (rows × columns), multiplication tables, generating all pairs.经典用途:处理网格(行 × 列)、乘法表、生成所有配对。
  • CSE1120 outcome 2.8.2 names "nested iterative blocks" explicitly. ICS3U A2.3 requires nested structures.CSE1120 结果 2.8.2 明确命名"嵌套迭代块"。ICS3U A2.3 要求嵌套结构。
Key trap: each loop must have its own distinct counter variable (use i for outer, j for inner). Re-using the same variable in both loops causes a logic error.关键陷阱:每个循环必须有各自独立的计数器变量(外层用 i,内层用 j)。在两个循环中重用同一变量会导致逻辑错误(logic error,逻辑错误)。
WE
Worked Example 7 · 3×3 multiplication table例题 7 · 3×3 乘法表

Print a multiplication table for rows 1–3 and columns 1–3.打印行 1–3、列 1–3 的乘法表。

FOR i FROM 1 TO 3:          -- outer loop: rows
    FOR j FROM 1 TO 3:      -- inner loop: columns
        OUTPUT i * j
    END FOR
END FOR

The outer loop gives i the values 1, 2, 3; for each value of i, the inner loop gives j the values 1, 2, 3 and outputs i*j. There are 9 outputs in total.外层 i 取 1, 2, 3;对于 i 的每个值,内层 j 取 1, 2, 3,输出 i*j。共 9 次输出。

for i in range(1, 4):       # outer: rows 1, 2, 3
    for j in range(1, 4):   # inner: columns 1, 2, 3
        print(i * j, end=" ")
    print()                 # newline after each row

print(i * j, end=" ") replaces the newline with a space; at the end of each outer-loop iteration, a bare print() outputs a newline, producing the table layout. Output:print(i * j, end=" ") 用空格替代换行;外层循环每次结束时 print() 输出换行,产生表格格式。输出:

1 2 3
2 4 6
3 6 9
An outer loop runs 4 times and an inner loop runs 5 times. How many times does the inner loop body execute in total?外层循环运行 4 次,内层循环运行 5 次。内层循环体总共执行多少次?
§7 · Q1
9
5
20
4
Total = outer × inner = 4 × 5 = 20. For each of the 4 outer iterations, the inner loop body runs 5 times.总次数 = 外层 × 内层 = 4 × 5 = 20。外层每次迭代,内层循环体运行 5 次。
Nested loops multiply: outer × inner = 4 × 5 = 20 total inner-body executions.嵌套循环相乘:外层 × 内层 = 4 × 5 = 20 次内层循环体执行。
Trace the nested loop below. What is the last value printed?
for i in range(1,3):
  for j in range(1,3):
    print(i + j)
追踪以下嵌套循环。最后打印的值是什么?
for i in range(1,3):
  for j in range(1,3):
    print(i + j)
§7 · Q2
2
3
5
4
range(1,3) gives 1,2. Sequence: i=1,j=1→2; i=1,j=2→3; i=2,j=1→3; i=2,j=2→4. Last printed: 4.range(1,3) 给出 1,2。序列:i=1,j=1→2;i=1,j=2→3;i=2,j=1→3;i=2,j=2→4。最后打印:4。
range(1,3)=[1,2]. Last pair: i=2,j=2 → 2+2=4.range(1,3)=[1,2]。最后一对:i=2,j=2 → 2+2=4。

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

Control flow questions appear in every CS exam format: multiple-choice trace, written pseudocode, short-answer justify. The tactics below cover the three most common failure modes.控制流程问题出现在每种 CS 考试形式中:多项选择追踪、书面伪代码、简答论证。以下策略涵盖三种最常见的失分模式。

Before any control-flow question任何控制流程题之前
  • Trace with a concrete value first.先用具体值追踪。 Before answering any loop or conditional question, substitute a real number and execute the pseudocode step by step. This catches off-by-one errors and wrong condition directions in 60 seconds.在回答任何循环或条件题之前,代入一个真实数字,逐步执行伪代码。这能在 60 秒内发现差一错误(off-by-one,差一错误)和条件方向错误。
  • Justify your loop choice (CSTA 3A-AP-15).论证你的循环选择(CSTA 3A-AP-15)。 If asked "why for vs while?": for = known count / iterating a collection; while = unknown repetitions, condition-dependent. Two sentences with the reason scores full marks.若被问"为何选 for 而非 while?":for = 已知次数/遍历集合;while = 未知次数、条件依赖。两句话说明原因即可满分。
Boolean and selection traps (§1-§3)布尔与选择陷阱(§1-§3)
  • Assignment vs comparison.赋值与比较。 x = 5 sets; x == 5 tests. In AP CSP pseudocode, assignment uses the arrow (). Mixing these up is the single most common error.x = 5 赋值;x == 5 测试。在 AP CSP 伪代码中,赋值使用箭头()。混淆两者是最常见的错误。
  • Condition direction in grade classifiers.等级分类器中的条件方向。 Conditions must go high-to-low (≥90, ≥80, ≥70 …). Low-to-high means every score ≥60 matches the first branch and you never reach A or B.条件必须从高到低(≥90,≥80,≥70……)。从低到高意味着每个 ≥60 的成绩都匹配第一个分支,永远不会达到 A 或 B。
Loop traps (§4-§7)循环陷阱(§4-§7)
  • Off-by-one.差一错误。 WHILE i < 5 iterates for i=1,2,3,4 (misses 5). WHILE i <= 5 iterates for i=1,2,3,4,5. Always trace the first and last value before submitting.WHILE i < 5 对 i=1,2,3,4 迭代(遗漏 5)。WHILE i <= 5 对 i=1,2,3,4,5 迭代。提交前始终追踪第一个和最后一个值。
  • range(start, stop) excludes stop.range(start, stop) 不含 stop。 range(1, 6) gives 1,2,3,4,5. To include n, write range(1, n+1).range(1, 6) 给出 1,2,3,4,5。要包含 n,写 range(1, n+1)。
  • Nested-loop total.嵌套循环总数。 Always compute outer × inner as a sanity check. That product is the answer to "how many times does the body run?"始终计算外层 × 内层(nested loop,嵌套循环)作为合理性检查。那个乘积就是"循环体运行多少次?"的答案。
Answer hygiene作答规范
  • Show your trace table explicitly.明确展示追踪表。 Column headers = variable names; rows = steps. A partial trace that reaches the error earns marks. "I calculated it mentally" earns zero.列标题 = 变量名;行 = 步骤。到达错误的部分追踪可得分。"我在脑中计算了"得零分。
  • Use the correct term: selection vs iteration.使用正确术语:选择与迭代。 ICS3U A2.2 uses "sequence, selection, and repetition." CSTA and AP CSP use "conditionals" and "iteration." Match the vocabulary of your curriculum.ICS3U A2.2 使用"顺序、选择(selection,选择)和重复"。CSTA 和 AP CSP 使用"条件语句"和"迭代(iteration,迭代)"。与你的课程词汇匹配。

Flashcards闪卡

0 / 14 flipped0 / 14 已翻
Boolean expression布尔表达式
An expression that evaluates to True or False. Built from comparison operators (==, !=, <, >, <=, >=) combined with and, or, not.求值为 True 或 False 的表达式。由比较运算符(==, !=, <, >, <=, >=)与 and、or、not 组合构成。
= vs === 与 ==
= is assignment (stores a value). == is comparison (tests equality). x = 5 sets x; x == 5 checks if x is 5.= 是赋值(存储值)。== 是比较(测试相等)。x = 5 设置 x;x == 5 检查 x 是否为 5。
if / elif / else templateif / elif / else 模板
Only one branch executes. Conditions checked top-to-bottom; first True branch runs; rest skipped. ICS3U A2.2 selection.只有一个分支执行。条件从上到下检查;第一个为 True 的分支运行;其余跳过。ICS3U A2.2 选择。
Nested conditional嵌套条件
An if/elif/else inside another if. Inner block only runs if outer condition is True. CSE1120 outcome 2.8.1; ICS3U A2.3.一个 if 嵌套在另一个 if 内部。内层块只在外层条件为 True 时运行。CSE1120 结果 2.8.1;ICS3U A2.3。
while loopwhile 循环
Repeats while condition is True; condition checked before each iteration. Use when number of iterations is unknown. Danger: infinite loop if condition never becomes False.条件为 True 时重复;每次迭代前检查条件。当迭代次数未知时使用。危险:若条件永不变 False 则无限循环。
for loopfor 循环
Iterates over a sequence (list, range). Loop variable takes each value in turn. Use when count is known. Python: range(start, stop) — stop is excluded.遍历序列(列表、范围)。循环变量依次取每个值。已知次数时使用。Python:range(start, stop)——stop 不含在内。
range(1, n+1)range(1, n+1)
Generates 1, 2, …, n. range(start, stop) excludes stop — must write n+1 to include n. Classic off-by-one trap.生成 1, 2, …, n。range(start, stop) 不含 stop——必须写 n+1 以包含 n。经典差一陷阱。
breakbreak(中断)
Exits the innermost loop immediately. Execution continues after the loop. Use to stop as soon as a target is found.立即退出最内层循环。执行在循环后继续。在找到目标时立即停止时使用。
continuecontinue(继续)
Skips the rest of the current iteration and returns to the loop condition. Does not exit the loop. Use to filter/skip items.跳过当前迭代的剩余部分,返回循环条件。不退出循环。用于过滤/跳过项目。
Nested loop total iterations嵌套循环总迭代次数
Total = outer count × inner count. E.g., outer runs 3 times, inner runs 4 times → 12 total body executions. CSE1120 outcome 2.8.2.总次数 = 外层次数 × 内层次数。例如,外层 3 次,内层 4 次 → 共 12 次循环体执行。CSE1120 结果 2.8.2。
Off-by-one error差一错误
Loop runs one too many or too few times. WHILE i < 5 misses 5; fix: WHILE i <= 5. Always trace boundary values.循环多一次或少一次。WHILE i < 5 遗漏 5;修复:WHILE i <= 5。始终追踪边界值。
Infinite loop无限循环
A while loop whose condition never becomes False. Caused by failing to update the variable the condition depends on. Program runs forever.条件永不变为 False 的 while 循环。由于未更新条件所依赖的变量而导致。程序永远运行。
CSTA 3A-AP-15CSTA 3A-AP-15
"Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance." Requires reasoning about for vs while, nesting depth, etc."当权衡涉及实现、可读性和程序性能时,论证选择特定控制结构的理由。"要求推理 for 与 while 的选择、嵌套深度等。
ICS3U A2.2 + A2.3ICS3U A2.2 + A2.3
A2.2: "use sequence, selection, and repetition control structures." A2.3: "write algorithms with nested structures." Core Ontario control-flow expectations.A2.2:"使用顺序、选择和重复控制结构。" A2.3:"编写具有嵌套结构的算法。" 安大略核心控制流程期望。

Practice Quiz综合测验

What is the output of if 7 >= 7: print("yes") else: print("no")?if 7 >= 7: print("yes") else: print("no") 的输出是什么?
Q1
no
Both "yes" and "no""yes" 和 "no" 都输出
Nothing什么都不输出
yes
7 >= 7 is True (7 equals 7, satisfying ≥). The if branch runs; else is skipped. Output: yes.7 >= 7 为 True(7 等于 7,满足 ≥)。if 分支运行;else 跳过。输出:yes。
7 >= 7 is True — >= includes equality. So the if branch runs, printing "yes".7 >= 7 为 True——>= 包含等于。所以 if 分支运行,打印 "yes"。
Trace: x = 0; while x < 3: x += 1. What is x when the loop ends?追踪:x = 0; while x < 3: x += 1。循环结束时 x 是多少?
Q2
2
3
4
Infinite loop无限循环
x: 0→1 (True), 1→2 (True), 2→3 (True), check 3<3 = False, loop exits. x = 3.x:0→1(True),1→2(True),2→3(True),检查 3<3 = False,循环退出。x = 3。
x increments to 3 before the condition becomes False. Final x = 3.x 增加到 3 后条件变为 False。最终 x = 3。
What does for i in range(0, 5): print(i) print?for i in range(0, 5): print(i) 打印什么?
Q3
0 1 2 3 4 5
1 2 3 4 5
0 1 2 3 4
1 2 3 4
range(0, 5) gives 0, 1, 2, 3, 4. Stop value 5 is excluded.range(0, 5) 给出 0, 1, 2, 3, 4。stop 值 5 不含在内。
range(start, stop) excludes stop. range(0,5) = 0,1,2,3,4.range(start, stop) 不含 stop。range(0,5) = 0,1,2,3,4。
Outer loop runs 5 times, inner loop runs 3 times. How many total inner-body executions?外层循环运行 5 次,内层循环运行 3 次。内层循环体共执行多少次?
Q4
15
8
5
3
Total = 5 × 3 = 15. For each of the 5 outer iterations, the inner body runs 3 times.总次数 = 5 × 3 = 15。外层每次迭代,内层循环体运行 3 次。
Nested loops multiply: outer × inner = 5 × 3 = 15.嵌套循环相乘:外层 × 内层 = 5 × 3 = 15。
A loop is supposed to sum 1+2+3+4+5 = 15, but outputs 10. It doesn't crash. What type of error?一个循环本应求 1+2+3+4+5 = 15,但输出 10。它不崩溃。是什么类型的错误?
Q5
Syntax error语法错误
Runtime error运行时错误
Logic error (off-by-one: condition should be <= 5)逻辑错误(差一:条件应为 <= 5)
No error没有错误
Runs without crash (not syntax/runtime). Wrong answer = logic error. Classic off-by-one: WHILE i < 5 stops before adding 5. Fix: i <= 5.运行不崩溃(不是语法/运行时错误)。答案错误 = 逻辑错误。经典差一:WHILE i < 5 在加 5 前停止。修复:i <= 5。
No crash = not syntax/runtime. Wrong output = logic error (off-by-one).不崩溃 = 不是语法/运行时。输出错误 = 逻辑错误(差一)。
Which CSTA standard (verbatim) asks you to justify your choice of control structure? 🇺🇸 CSTA哪个 CSTA 标准(原文)要求你论证控制结构的选择?🇺🇸 CSTA
Q6
3A-AP-13
3A-AP-15
3B-AP-10
3A-AP-17
CSTA 3A-AP-15 (verbatim): "Justify the selection of specific control structures when tradeoffs involve implementation, readability, and program performance."CSTA 3A-AP-15(原文):"当权衡涉及实现、可读性和程序性能时,论证选择特定控制结构的理由。"
3A-AP-15 = control structure justification. 3A-AP-13 = prototypes/algorithms. 3B-AP-10 = classic algorithms. 3A-AP-17 = decomposition.3A-AP-15 = 控制结构论证。3A-AP-13 = 原型/算法。3B-AP-10 = 经典算法。3A-AP-17 = 分解。
Ontario ICS3U expectation A2.3 (verbatim) requires students to write algorithms with what feature? 🇨🇦 ON安大略 ICS3U 期望 A2.3(原文)要求学生编写具有什么特征的算法?🇨🇦 ON
Q7
Nested structures嵌套结构
Recursion递归
Object-oriented classes面向对象类
File input/output文件输入/输出
ICS3U A2.3 (verbatim): "write algorithms with nested structures (e.g., to count elements in an array, calculate a total, find highest or lowest value, or perform a linear search)."ICS3U A2.3(原文):"编写具有嵌套结构的算法(如计算数组元素、求总和、查找最大/最小值或执行线性搜索)。"
A2.3 requires nested structures. Recursion is ICS4U. OOP and file I/O are other ICS4U topics.A2.3 要求嵌套结构。递归是 ICS4U 内容。OOP 和文件 I/O 是其他 ICS4U 主题。

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本单元的去向

Control flow is the engine that makes programs useful. Every subsequent HS CS unit builds on the selection and iteration constructs practiced here: Functions (Unit 4) use conditionals inside function bodies; Data Structures (Unit 5) use for loops to traverse lists; Searching and Sorting (Unit 7) is nested loops and conditionals throughout. Both AP courses also assume control-flow fluency from day one.控制流程是让程序有用的引擎。后续每个 HS CS 单元都建立在这里练习的选择和迭代构造之上:函数(第 4 单元)在函数体内使用条件语句;数据结构(第 5 单元)使用 for 循环遍历列表;搜索与排序(第 7 单元)通篇是嵌套循环(nested loops,嵌套循环)和条件语句。两门 AP 课程也从第一天起就假定控制流程流利度。

AP feeder link (confirmed in this repo).AP 衔接链接(本仓库中已确认)。

AP CSA Unit 2 · Selection and Iteration (Java if/else, while, for — the direct AP CSA counterpart of every section in this guide)AP CSA Unit 2 · 选择与迭代(Java if/else、while、for——本指南每节的直接 AP CSA 对应)

AP CSP Big Idea 3 topics 3.5–3.8 (Boolean expressions, conditionals, nested conditionals, iteration) map exactly to §1–§5 of this guide. AP CSA Unit 2 uses the same constructs in Java syntax — the logic and trace-table skills transfer directly. Mastering all seven sections before either AP eliminates the steepest learning-curve spike in the first weeks.AP CSP 大概念 3 主题 3.5–3.8(布尔表达式、条件语句、嵌套条件、迭代)恰好对应本指南的 §1–§5。AP CSA 第 2 单元使用相同构造的 Java 语法——逻辑和追踪表(trace table,追踪表)技能可直接迁移。在任一 AP 课程之前掌握全部七节,可消除前几周最陡峭的学习曲线。