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 例题

Boolean Conditions & Comparison布尔条件与比较

Learning objectives学习目标
  • Evaluate comparison expressions and compound Boolean expressions built with and, or and not for given values.
  • Apply the precedence order not, then and, then or, and use parentheses to make the intended grouping explicit.
  • Tell assignment (=) from comparison (==) and say which one a condition needs.
  • 对给定的值,求值比较表达式以及由 and、or、not 构成的复合布尔表达式。
  • 应用优先级顺序(先 not,再 and,最后 or),并用括号明确想要的分组。
  • 区分赋值(=)与比较(==),并说明条件中需要哪一个。
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,布尔表达式)求值为 True 或 False。用 and(与)、or(或)、not(非)组合。关键陷阱:x = 5 是赋值;x == 5 是测试。CSE1120 结果 2.6 明确命名"关系、布尔"运算符。
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(假)。

Worked Example 2: Compound conditions and precedence例题 2:复合条件与运算优先级

Problem: a cinema gives a discount to a customer who is 65 or older or is a student, but only if the customer is a member. Decide whether a 70-year-old non-student member gets the discount, then show why the brackets matter.问题:电影院给 65 岁及以上或是学生的顾客折扣,但前提是该顾客是会员。判断一位 70 岁、非学生的会员能否获得折扣,并说明括号为什么重要。

SET age TO 70
SET is_student TO False
SET member TO True
SET eligible TO (age >= 65 OR is_student) AND member
OUTPUT eligible
OUTPUT NOT eligible

Evaluate inside the brackets first: age >= 65 is True, is_student is False, and True OR False is True. Then True AND member (True) is True, so eligible is True and NOT eligible is False.先算括号内:age >= 65 为 True,is_student 为 False,True OR False 为 True。再算 True AND member(True)为 True,所以 eligible 为 True,NOT eligible 为 False。

age = 70
is_student = False
member = True
eligible = (age >= 65 or is_student) and member
print(eligible)         # True
print(not eligible)     # False
print(age >= 65 and is_student)   # False

Python prints True, False, False. The last line shows that and needs both sides True: age >= 65 is True but is_student is False.Python 依次输出 True、False、False。最后一行说明 and 要求两边都为 True:age >= 65 为 True,但 is_student 为 False。

Precedence trap. not is applied first, then and, then or. Take a 70-year-old who is not a student and is not a member. The correct rule gives False, but dropping the brackets gives True:优先级陷阱。先算 not,再算 and,最后算 or。设一位 70 岁、非学生、非会员的顾客。正确规则应得 False,但去掉括号后得到 True:

age = 70
is_student = False
member = False
print((age >= 65 or is_student) and member)   # False: members only
print(age >= 65 or is_student and member)     # True: and binds first
print(True or False and False)                 # True
print((True or False) and False)               # False

Without brackets, is_student and member is grouped first (False and False is False), and then age >= 65 or False is True: the non-member wrongly gets the discount. Brackets make the intended grouping visible and cost nothing.没有括号时,先分组的是 is_student and member(False and False 为 False),然后 age >= 65 or False 为 True:非会员被错误地给了折扣。括号让预期的分组一目了然,而且没有任何代价。

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。
Exam tip考试提示

Questions use command words such as evaluate, state the value and trace. Write True or False under each sub-expression before combining them, and say which operator runs first. Common errors: writing = where a condition needs ==, and forgetting that and runs before or. A bare final value with no working shown is an incomplete answer.

题目常用的指令词有求值、写出值和追踪。在组合之前,先在每个子表达式下写出 True 或 False,并说明哪个运算符先执行。常见错误:在需要 == 的条件里写成 =,以及忘记 and 先于 or 执行。只写最终结果而不展示过程,是不完整的答案。

Check your understanding自我检测
With x = 7, evaluate x > 5 and x < 7.当 x = 7 时,求值 x > 5 and x < 7。

x > 5 is True (7 > 5). x < 7 is False (7 is not less than 7). True and False is False.

x > 5 为 True(7 > 5)。x < 7 为 False(7 不小于 7)。True and False 为 False。

With x = 7, evaluate not (x == 7) or x >= 7.当 x = 7 时,求值 not (x == 7) or x >= 7。

x == 7 is True, so not (x == 7) is False. x >= 7 is True. False or True is True.

x == 7 为 True,所以 not (x == 7) 为 False。x >= 7 为 True。False or True 为 True。

A student writes if score = 90: to test for a score of exactly 90. What is wrong, and what is the fix?一位学生写了 if score = 90: 来测试分数是否恰好为 90。错在哪里?如何修正?

= assigns a value and is not allowed inside an if condition, so Python reports a syntax error. A condition needs the comparison operator: if score == 90:.

= 用于赋值,不能出现在 if 条件中,所以 Python 会报语法错误。条件需要比较运算符:if score == 90:。


if / elif / elseif / elif / else

Learning objectives学习目标
  • Write an if/elif/else chain with three or more branches in pseudocode and in Python.
  • Order the conditions so that the first branch that is True is the correct one, and explain why exactly one branch runs.
  • Test a chain with boundary values (for example 17, 18 and 65) and tell an elif chain from a series of separate if statements.
  • 用伪代码和 Python 编写包含三个或更多分支的 if/elif/else 链。
  • 安排条件的顺序,使第一个为 True 的分支恰好是正确的分支,并解释为什么只有一个分支运行。
  • 用边界值(例如 17、18 和 65)测试条件链,并区分 elif 链与一连串独立的 if 语句。
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 为嵌套条件。
START开始 INPUT score输入 score score ≥ 90?score ≥ 90? yes是 Output A输出 A no否 score ≥ 80?score ≥ 80? yes是 Output B输出 B no否 score ≥ 70?score ≥ 70? yes是 Output C输出 C no否 score ≥ 60?score ≥ 60? yes是 Output D输出 D no否 Output F输出 F END结束
Figure 1. The if/elif/else chain of Worked Example 3 as a flowchart. Each diamond has one yes exit and one no exit, and the tests run from the top down. The highlighted path is score = 75: 75 ≥ 90 is no, 75 ≥ 80 is no, 75 ≥ 70 is yes, so the output is C and the lower tests are never evaluated.图 1. 例题 3 的 if/elif/else 链画成流程图。每个菱形有一个“是”出口和一个“否”出口,测试自上而下依次进行。高亮路径对应 score = 75:75 ≥ 90 为否,75 ≥ 80 为否,75 ≥ 70 为是,所以输出 C,下面的测试不会再执行。
Worked Example 3: Letter grade classifier例题 3:字母等级分类

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,缩进)标记代码块。

Worked Example 4: A bus fare chain and the order of its conditions例题 4:公交票价条件链及条件顺序

Problem: a bus fare in dollars depends on age. Children under 5 ride free; ages 5 to 17 pay 2; ages 18 to 64 pay 4; ages 65 and over pay 2. Write the chain, test the boundary ages, then show what happens if two conditions are in the wrong order.问题:公交票价(单位:美元)取决于年龄。5 岁以下儿童免费;5 至 17 岁付 2;18 至 64 岁付 4;65 岁及以上付 2。写出条件链,测试边界年龄,然后说明两个条件顺序错误时会发生什么。

INPUT age
IF age < 5 THEN
    SET fare TO 0
ELIF age < 18 THEN
    SET fare TO 2
ELIF age < 65 THEN
    SET fare TO 4
ELSE
    SET fare TO 2
END IF
OUTPUT fare

Each ELIF is reached only when every test above it was False, so age < 18 really means ages 5 to 17 and age < 65 means ages 18 to 64. The ELSE catches 65 and over.只有当上面所有测试都为 False 时才会到达某个 ELIF,所以 age < 18 实际表示 5 至 17 岁,age < 65 表示 18 至 64 岁。ELSE 接住 65 岁及以上。

age = int(input())
if age < 5:
    fare = 0
elif age < 18:
    fare = 2
elif age < 65:
    fare = 4
else:
    fare = 2
print(fare)

Boundary test (the values just below and just above each cut-off): age 4 gives 0, age 5 gives 2, age 17 gives 2, age 18 gives 4, age 64 gives 4, age 65 gives 2. Every cut-off flips the branch exactly where the problem says it should.边界测试(每个分界点前后的值):年龄 4 得 0,年龄 5 得 2,年龄 17 得 2,年龄 18 得 4,年龄 64 得 4,年龄 65 得 2。每个分界点都恰好在题目要求的位置切换分支。

Wrong order. Put the broadest test before a narrower one and the narrower branch can never run:顺序错误。把范围最宽的测试放在较窄的测试之前,较窄的分支就永远不会运行:

age = 10
if age < 5:
    fare = 0
elif age < 65:      # catches every age from 5 to 64
    fare = 4
elif age < 18:      # never reached
    fare = 2
else:
    fare = 2
print(fare)         # 4, but a 10-year-old should pay 2

The 10-year-old is caught by age < 65 first, so the program prints 4 instead of 2. Order the tests from the narrowest range to the widest, and re-run the boundary ages after any change.10 岁的乘客先被 age < 65 接住,所以程序输出 4 而不是 2。应把测试按范围从窄到宽排列,并在每次改动后重新测试边界年龄。

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" 被跳过。
Exam tip考试提示

Command words here are trace, complete the code and write a chain. Always test the boundary values, the numbers on either side of each cut-off, because that is where < versus <= mistakes show up. Common errors: putting a wide condition before a narrow one, and using separate if statements where the branches should be exclusive, so that two branches run.

这里的指令词是追踪、补全代码和编写条件链。务必测试边界值,即每个分界点两侧的数,因为 < 与 <= 的错误正是出现在那里。常见错误:把宽条件放在窄条件之前,以及在分支应当互斥的地方使用独立的 if 语句,导致两个分支都运行。

Check your understanding自我检测
A chain prints high if x > 10, otherwise mid if x > 5, otherwise low. What does it print for x = 12? What is printed if the three tests are written as if x > 10 and then a separate if x > 5 with an else for low?一个条件链:若 x > 10 输出 high,否则若 x > 5 输出 mid,否则输出 low。x = 12 时输出什么?如果写成 if x > 10,再另起一个 if x > 5 并让 else 输出 low,会输出什么?

The chain prints only high: the first test is True and the rest are skipped. With a separate second if, both x > 10 and x > 5 are True, so the program prints high and then mid.

条件链只输出 high:第一个测试为 True,其余被跳过。第二个 if 独立时,x > 10 与 x > 5 都为 True,所以程序先输出 high,再输出 mid。

In the grade classifier of Worked Example 3, the first test is changed to if score >= 60 and the other tests stay below it. What letter is printed for score = 95?在例题 3 的等级分类中,把第一个测试改成 if score >= 60,其余测试仍在它下面。score = 95 时输出什么字母?

D. 95 ≥ 60 is True, so the first branch (which outputs D) runs and every other test is skipped. The tests must go from the highest cut-off to the lowest.

D。95 ≥ 60 为 True,所以第一个分支(输出 D)运行,其余测试全被跳过。测试必须从最高分界点排到最低分界点。

In Worked Example 4, which ages pay a fare of 2?在例题 4 中,哪些年龄的票价是 2?

Ages 5 to 17 (the age < 18 branch) and ages 65 and over (the else branch). Ages 0 to 4 pay 0 and ages 18 to 64 pay 4.

5 至 17 岁(age < 18 分支)和 65 岁及以上(else 分支)。0 至 4 岁付 0,18 至 64 岁付 4。


Nested Conditionals嵌套条件

Learning objectives学习目标
  • Write a nested conditional (an if inside an if) in pseudocode and Python and trace which branch runs for given inputs.
  • Explain why the inner block is skipped when the outer condition is False, and match each else to its if by indentation.
  • Rewrite a nested conditional as a flatter chain with and/elif and check that both versions give the same results.
  • 用伪代码和 Python 编写嵌套条件(if 内嵌 if),并追踪给定输入下哪个分支运行。
  • 解释外层条件为 False 时为何跳过内层块,并通过缩进把每个 else 与其对应的 if 配对。
  • 把嵌套条件改写成更扁平的 and/elif 形式,并检查两个版本结果相同。
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 要求你从可读性角度论证控制结构选择。
Worked Example 5: Theme-park entry check例题 5:主题乐园入场检查

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 个空格。

Worked Example 6: Leap year test with three levels of nesting例题 6:用三层嵌套判断闰年

Problem: a year is a leap year if it is divisible by 4, except that century years (divisible by 100) are leap years only when also divisible by 400. Write the test as a nested conditional and trace the years 2023, 2024, 1900 and 2000.问题:能被 4 整除的年份是闰年,但世纪年(能被 100 整除)只有同时能被 400 整除才是闰年。把该判断写成嵌套条件,并追踪 2023、2024、1900 和 2000 年。

INPUT year
IF year MOD 4 = 0 THEN
    IF year MOD 100 = 0 THEN
        IF year MOD 400 = 0 THEN
            OUTPUT "leap"
        ELSE
            OUTPUT "not leap"
        END IF
    ELSE
        OUTPUT "leap"
    END IF
ELSE
    OUTPUT "not leap"
END IF

Each level asks one question and only runs when the level above was True: divisible by 4? then by 100? then by 400? The year 1900 passes the first two questions and fails the third.每一层只问一个问题,并且只有上一层为 True 时才会运行:能被 4 整除吗?再问能被 100 整除吗?再问能被 400 整除吗?1900 年通过前两个问题,却在第三个问题上失败。

year = int(input())
if year % 4 == 0:
    if year % 100 == 0:
        if year % 400 == 0:
            print("leap")
        else:
            print("not leap")
    else:
        print("leap")
else:
    print("not leap")

Trace: 2023 % 4 is 3, so the outer test fails and the program prints not leap. 2024 % 4 is 0 and 2024 % 100 is 24, so the middle test fails and it prints leap. 1900 % 4 is 0, 1900 % 100 is 0 and 1900 % 400 is 300, so it prints not leap. 2000 % 400 is 0, so it prints leap.追踪:2023 % 4 为 3,外层测试失败,程序输出 not leap。2024 % 4 为 0 且 2024 % 100 为 24,中层测试失败,输出 leap。1900 % 4 为 0,1900 % 100 为 0,1900 % 400 为 300,输出 not leap。2000 % 400 为 0,输出 leap。

Flatter version. The same rule fits in one Boolean expression, which is easier to read once you trust the logic. Both versions agree on all four test years:更扁平的版本。同一规则可以写成一个布尔表达式,理清逻辑后更易阅读。两个版本在这四个测试年份上结果一致:

year = int(input())
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print("leap")
else:
    print("not leap")

Check: 2024 gives True (divisible by 4, not by 100), 1900 gives False (divisible by 100 but not by 400), 2000 gives True (divisible by 400), and 2023 gives False. Keep the nested form when each level needs its own message; use the flat form when only the final result matters.核对:2024 为 True(能被 4 整除,不能被 100 整除),1900 为 False(能被 100 整除但不能被 400 整除),2000 为 True(能被 400 整除),2023 为 False。若每一层都需要各自的提示信息,就保留嵌套形式;若只关心最终结果,就用扁平形式。

In the theme-park example, what is the output when age = 10 and height = 150?在主题乐园例题中,当 age = 10、height = 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 不执行。
Exam tip考试提示

Command words: trace, explain and rewrite. To trace a nested conditional, follow the indentation: an else belongs to the if at the same indentation level, not to the nearest if above it on the page. Common errors: reading the inner test when the outer test is False, and mis-indenting an else so that it pairs with the wrong if.

指令词:追踪、解释和改写。追踪嵌套条件时要跟着缩进走:else 属于缩进层级相同的 if,而不是页面上离它最近的上方 if。常见错误:外层测试为 False 时仍去读内层测试,以及把 else 缩进错误,使它与错误的 if 配对。

Check your understanding自我检测
Use the leap-year code of Worked Example 6. Which test fails first for year = 1900, and what is printed?使用例题 6 的闰年代码。year = 1900 时哪个测试最先失败?输出什么?

The first two tests pass (1900 % 4 = 0 and 1900 % 100 = 0). The innermost test year % 400 == 0 fails because 1900 % 400 = 300, so its else prints not leap.

前两个测试通过(1900 % 4 = 0,1900 % 100 = 0)。最内层测试 year % 400 == 0 失败,因为 1900 % 400 = 300,所以它的 else 输出 not leap。

In the theme-park program of Worked Example 5, what is printed for age = 14 and height = 130? Which input values print Enjoy the ride!?在例题 5 的主题乐园程序中,age = 14、height = 130 时输出什么?哪些输入会输出 Enjoy the ride!?

It prints Too short.: 14 ≥ 12 passes the outer test, then 130 ≥ 140 fails. Enjoy the ride! needs both age >= 12 and height >= 140 to be True.

输出 Too short.:14 ≥ 12 通过外层测试,随后 130 ≥ 140 失败。输出 Enjoy the ride! 需要 age >= 12 与 height >= 140 同时为 True。

Rewrite the theme-park program without nesting, using one if, one elif and one else.不使用嵌套,改用一个 if、一个 elif 和一个 else 重写主题乐园程序。

if age < 12: print Too young.; elif height < 140: print Too short.; else: print Enjoy the ride!. The elif is reached only when age >= 12, so it gives the same three outcomes as the nested version.

if age < 12: 输出 Too young.;elif height < 140: 输出 Too short.;else: 输出 Enjoy the ride!。只有 age >= 12 时才会到达 elif,所以它与嵌套版本给出相同的三种结果。


while Loopswhile 循环

Learning objectives学习目标
  • Trace a while loop with a variable table and state how many times its body runs (including zero times).
  • Identify what must be updated inside the body to avoid an infinite loop, and fix a loop that never ends.
  • Write an input-validation loop whose condition is the opposite of what counts as valid.
  • 用变量表追踪 while 循环,并说明其循环体运行多少次(包括零次)。
  • 找出循环体内必须更新的内容以避免无限循环,并修正一个永不结束的循环。
  • 编写输入验证循环,其条件与“有效”的含义相反。
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 命名"迭代(重复)"。
START开始 SET count TO 5令 count = 5 count ≥ 1?count ≥ 1? yes是 OUTPUT count输出 count count = count − 1count = count − 1 repeat回路 no否 Output Blast off!输出 Blast off! END结束
Figure 2. The countdown loop of Worked Example 7 as a flowchart. The test is checked before every pass, and the highlighted arrow is the loop-back that returns to it. With count starting at 5 the yes exit is taken five times (outputs 5, 4, 3, 2, 1); when count reaches 0 the test is no and the program prints Blast off!图 2. 例题 7 的倒计时循环画成流程图。每一轮之前都要检查测试,高亮箭头是返回测试的回路。count 从 5 开始,“是”出口走五次(输出 5、4、3、2、1);当 count 变为 0 时测试为“否”,程序输出 Blast off!
Worked Example 7: Countdown with while例题 7:用 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 -= 1 是 count = 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,循环体无限重复,无限循环。这是逻辑错误,不是语法错误。
Worked Example 8: Input validation with while例题 8:用 while 做输入验证

Problem: keep asking the user for a number between 1 and 10 (inclusive) until they enter a valid one.问题:反复要求用户输入一个 1 到 10(含)之间的数字,直到输入有效为止。

INPUT n
WHILE n < 1 OR n > 10:
    OUTPUT "Invalid. Try again:"
    INPUT n
OUTPUT "Accepted: ", n

This is a common pattern called an input-validation loop: read a value first, then loop while it is invalid, re-reading inside the body. The loop condition is the opposite of what counts as valid: here valid means 1 ≤ n ≤ 10, so the loop repeats while n < 1 OR n > 10.这是常见的编程模式,称为输入验证循环(input-validation loop,输入验证循环):先读入一个值,然后在其无效时循环,在循环体内重新读入。循环条件与"有效"相反,此处有效指 1 ≤ n ≤ 10,故循环在 n < 1 OR n > 10 时重复。

n = int(input())
while n < 1 or n > 10:
    print("Invalid. Try again:")
    n = int(input())
print("Accepted:", n)

A frequent mistake is writing the loop condition as the valid range instead of its opposite (e.g. mistakenly writing while 1 <= n <= 10, which would re-prompt on a valid first entry and let an invalid first entry straight through). Always ask: "the loop keeps running while what is true?" Here, while the value is still bad.常见错误是把循环条件写成有效范围而非其反面(例如误写 while 1 <= n <= 10,这会在首次输入有效时反而要求重新输入,而首次输入无效时直接放行)。始终自问:"循环在什么条件为真时持续运行?",此处是当数值仍然无效时。

Exam tip考试提示

Command words: trace, state the number of iterations and fix the loop. Build a variable table with one column per variable and one row per pass, and test the condition again after the last row. Common errors: forgetting to update the variable the condition depends on (an infinite loop), choosing < where <= is needed so the last value is skipped, and forgetting that a loop whose condition is False on entry runs zero times.

指令词:追踪、说明迭代次数和修正循环。画变量表,每个变量一列,每一轮一行,并在最后一行之后再检查一次条件。常见错误:忘记更新条件所依赖的变量(无限循环)、该用 <= 时用了 < 导致漏掉最后一个值,以及忘记入口时条件为 False 的循环会运行零次。

Check your understanding自我检测
Trace n = 10 then while n > 0: with body n -= 3 and print(n). What is printed, how many times does the body run, and what is n at the end?追踪:n = 10,然后 while n > 0:,循环体为 n -= 3 和 print(n)。输出什么?循环体运行几次?结束时 n 是多少?

It prints 7, 4, 1, -2 (one per line). The body runs 4 times: n goes 10 → 7 → 4 → 1 → -2, and the test -2 > 0 is False. At the end n is -2, which is below zero because the step of 3 does not land on 0.

依次输出 7、4、1、-2(每行一个)。循环体运行 4 次:n 依次为 10 → 7 → 4 → 1 → -2,测试 -2 > 0 为 False。结束时 n 为 -2,因为步长 3 恰好不落在 0 上,所以会低于零。

This loop never ends: i = 1, while i <= 5:, print(i). Explain why and write the fix.这个循环永不结束:i = 1,while i <= 5:,print(i)。解释原因并写出修正。

Nothing in the body changes i, so i <= 5 stays True forever. Add i += 1 as the last line of the body; the loop then prints 1, 2, 3, 4, 5 and stops when i becomes 6.

循环体内没有任何语句改变 i,所以 i <= 5 永远为 True。在循环体最后加上 i += 1;这样循环输出 1、2、3、4、5,并在 i 变为 6 时停止。

How many times does the body of x = 10, while x < 5:, x += 1 run?x = 10,while x < 5:,x += 1 的循环体运行几次?

Zero times. The condition is checked before the first pass, and 10 < 5 is already False, so the body is skipped and x stays 10.

零次。条件在第一轮之前就检查,10 < 5 已经为 False,所以循环体被跳过,x 保持为 10。


for Loopsfor 循环

Learning objectives学习目标
  • Write a for loop over range(start, stop) or over a list, and list the values the loop variable takes.
  • Compute the number of iterations of range(start, stop) as stop - start, and choose n + 1 to include n.
  • Apply the running-total and running-maximum or minimum patterns, and choose between for and while for a given task.
  • 编写遍历 range(start, stop) 或列表的 for 循环,并列出循环变量依次取到的值。
  • 把 range(start, stop) 的迭代次数算成 stop - start,并用 n + 1 来包含 n。
  • 应用累计总和与滚动最大值或最小值的模式,并为给定任务在 for 与 while 之间做出选择。
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。
Worked Example 9: Sum of 1 to n with for例题 9:用 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。
Worked Example 10: Finding the maximum with a for loop例题 10:用 for 循环求最大值

Problem: given a list of exam scores, find the highest score without using a built-in max function.问题:给定一份考试成绩列表,在不使用内置 max 函数的情况下求最高分。

SET scores TO [72, 88, 65, 91, 79]
SET highest TO scores[0]
FOR i FROM 1 TO length(scores) - 1:
    IF scores[i] > highest THEN
        SET highest TO scores[i]
OUTPUT highest

This is the running-maximum pattern: seed highest with the first element (never with 0: that fails if every score were negative), then compare every remaining element against it, updating whenever a bigger value appears. The loop starts at index 1 because index 0 is already stored in highest.这是滚动最大值模式(running-maximum pattern,滚动最大值模式):用第一个元素初始化 highest(切勿用 0,如果所有成绩都是负数就会出错),然后将其余每个元素与之比较,一旦出现更大值就更新。循环从索引 1 开始,因为索引 0 已存入 highest。

scores = [72, 88, 65, 91, 79]
highest = scores[0]
for i in range(1, len(scores)):
    if scores[i] > highest:
        highest = scores[i]
print(highest)   # 91

Tracing it: highest starts at 72; 88>72 → highest=88; 65>88 is False, no change; 91>88 → highest=91; 79>91 is False. Final answer: 91. The same pattern with the comparison flipped (scores[i] < lowest) finds the minimum.追踪过程:highest 从 72 开始;88>72 → highest=88;65>88 为 False,不变;91>88 → highest=91;79>91 为 False。最终答案:91。将比较方向反转(scores[i] < lowest)即可用同一模式求最小值。

Exam tip考试提示

Command words: list the values, state the number of iterations and choose and justify. For range(a, b) write the first and last value and count b - a values. Common errors: expecting the stop value to be included, starting a running maximum from 0 instead of from the first element, and choosing for when the number of repetitions depends on a condition.

指令词:列出各值、说明迭代次数和选择并论证。对 range(a, b),写出第一个和最后一个值,并数出 b - a 个值。常见错误:以为 stop 值会被包含、用 0 而不是第一个元素来初始化滚动最大值,以及在重复次数取决于条件时选用 for。

Check your understanding自我检测
List the values of i in for i in range(2, 9) and state how many iterations there are.列出 for i in range(2, 9) 中 i 的各个值,并说明迭代次数。

i takes 2, 3, 4, 5, 6, 7, 8. The stop value 9 is excluded, so there are 9 - 2 = 7 iterations.

i 依次取 2、3、4、5、6、7、8。stop 值 9 不包含在内,所以有 9 - 2 = 7 次迭代。

Adapt the running-maximum code of Worked Example 10 to find the lowest score in [72, 88, 65, 91, 79]. Show the value of the running minimum after each comparison.改写例题 10 的滚动最大值代码,求 [72, 88, 65, 91, 79] 中的最低分。写出每次比较后滚动最小值的值。

Start lowest = 72 and change the test to scores[i] < lowest. 88 < 72 is False (72); 65 < 72 is True (65); 91 < 65 is False (65); 79 < 65 is False (65). The answer is 65.

令 lowest = 72,并把测试改为 scores[i] < lowest。88 < 72 为 False(72);65 < 72 为 True(65);91 < 65 为 False(65);79 < 65 为 False(65)。答案是 65。

Which loop fits each task: (a) print every name in a list of 30 names; (b) keep asking for a password until it is correct?下列任务各适合哪种循环:(a) 打印 30 个名字的列表中的每个名字;(b) 反复要求输入密码直到正确?

(a) a for loop, because the collection and its length are known. (b) a while loop, because the number of attempts is unknown and depends on a condition (the password being correct).

(a) 用 for 循环,因为集合及其长度已知。(b) 用 while 循环,因为尝试次数未知,取决于条件(密码是否正确)。


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

Learning objectives学习目标
  • Choose between break (leave the loop) and continue (skip to the next pass) for a given task.
  • Trace a loop that uses break or continue, including one inside a nested loop, and state the output.
  • Place the update of a while loop variable so that continue cannot skip it and cause an infinite loop.
  • 针对给定任务,在 break(离开循环)与 continue(跳到下一轮)之间做出选择。
  • 追踪使用 break 或 continue 的循环(包括嵌套循环中的情形)并写出输出。
  • 合理放置 while 循环变量的更新位置,使 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 学生将此节作为拓展内容。
Worked Example 11: Search with break; skip negatives with continue例题 11:用 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。

Worked Example 12: break, continue and a while loop together例题 12:在 while 循环中同时使用 break 与 continue

Problem: a list holds readings, where a negative value is a bad reading to skip and the value 0 marks the end of the data. Add up the good readings before the 0 in [5, -2, 8, 0, 9], then show what break does inside a nested loop.问题:列表保存一组读数,其中负数是应跳过的坏读数,数值 0 表示数据结束。对 [5, -2, 8, 0, 9] 中 0 之前的有效读数求和,然后说明 break 在嵌套循环内的作用。

SET data TO [5, -2, 8, 0, 9]
SET i TO 0
SET total TO 0
WHILE i < length(data):
    SET value TO data[i]
    SET i TO i + 1
    IF value = 0 THEN
        STOP THE LOOP
    IF value < 0 THEN
        SKIP TO NEXT PASS
    SET total TO total + value
OUTPUT total

The index i is advanced before the two tests. If the update came after them, a continue on a negative reading would jump back to the loop test without ever changing i, and the loop would repeat the same bad reading forever.索引 i 在两个测试之前就先前进。如果更新放在测试之后,遇到负读数时 continue 会直接跳回循环测试而没有改变 i,循环就会永远重复同一个坏读数。

data = [5, -2, 8, 0, 9]
i = 0
total = 0
while i < len(data):
    value = data[i]
    i += 1              # update first, so continue cannot skip it
    if value == 0:
        break           # 0 marks the end of the data
    if value < 0:
        continue        # skip a bad reading
    total += value
print(total)            # 13

Trace: 5 is added (total 5); -2 is skipped by continue; 8 is added (total 13); 0 triggers break, so 9 is never read. The program prints 13, and i is 4 when the loop ends.追踪:加入 5(total 为 5);-2 被 continue 跳过;加入 8(total 为 13);0 触发 break,所以 9 永远不会被读取。程序输出 13,循环结束时 i 为 4。

break in a nested loop leaves only the innermost loop. The outer loop carries on with its next value:嵌套循环中的 break 只离开最内层循环。外层循环会继续处理它的下一个值:

for i in range(1, 4):
    for j in range(1, 4):
        if j == 2:
            break
        print(i, j)

Each time the inner loop reaches j == 2 it stops, so only j = 1 is printed for every i. The output is 1 1, 2 1, 3 1, one pair per line: the outer loop still runs all three times.内层循环每次到达 j == 2 就停止,所以每个 i 只输出 j = 1 那一对。输出为 1 1、2 1、3 1(每行一对):外层循环仍然完整运行三次。

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 跳过当前轮次的剩余部分,移动到下一次迭代。
Exam tip考试提示

Command words: trace, state the output and explain the effect of a keyword. Flag on your trace table the pass where break or continue runs, and write what is skipped. Common errors: believing break ends the whole program or every nested loop, believing continue leaves the loop, and putting the while update after a continue.

指令词:追踪、写出输出和解释某个关键字的作用。在追踪表上标出 break 或 continue 运行的那一轮,并写明跳过了什么。常见错误:以为 break 会结束整个程序或所有嵌套循环、以为 continue 会离开循环,以及把 while 的更新放在 continue 之后。

Check your understanding自我检测
What does for n in [1, 2, 3, 4, 5]: with the body if n == 3: continue then print(n) print?for n in [1, 2, 3, 4, 5]:,循环体为 if n == 3: continue,然后 print(n)。会输出什么?

It prints 1, 2, 4, 5 (one per line). When n is 3, continue skips print(n) and the loop moves on to 4.

输出 1、2、4、5(每行一个)。n 为 3 时,continue 跳过 print(n),循环继续处理 4。

Change continue to break in the loop above. What is printed now?把上面循环中的 continue 改成 break。现在输出什么?

It prints 1 and 2. When n is 3, break leaves the loop, so 3, 4 and 5 are never printed.

输出 1 和 2。n 为 3 时,break 离开循环,所以 3、4、5 都不会被输出。

For for i in range(1, 3): containing for j in range(1, 4): with if j == 2: break before print(i, j), list the output.对 for i in range(1, 3):,其内含 for j in range(1, 4):,并在 print(i, j) 之前有 if j == 2: break,列出输出。

1 1 and 2 1. The inner break stops only the j loop at j == 2; the i loop still runs for 1 and 2, and each time only j = 1 is printed.

1 1 和 2 1。内层的 break 只在 j == 2 时停止 j 循环;i 循环仍对 1 和 2 各运行一次,每次只输出 j = 1。


Nested Loops嵌套循环

Learning objectives学习目标
  • Write nested for loops with a separate counter variable for each loop and trace them with a table of i and j.
  • Compute the total number of inner-body executions, multiplying when both bounds are fixed and adding when the inner bound depends on the outer variable.
  • Use a per-row accumulator inside an outer loop to build one line of output.
  • 编写嵌套 for 循环,每个循环使用各自独立的计数器变量,并用 i 与 j 的表格追踪它们。
  • 计算内层循环体的总执行次数:两个边界都固定时用乘法,内层边界取决于外层变量时用加法。
  • 在外层循环内使用逐行累加器来构造一行输出。
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,逻辑错误)。
Worked Example 13: 3×3 multiplication table例题 13: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。
Worked Example 14: Printing a right triangle of stars例题 14:打印星号直角三角形

Problem: print a right-triangle pattern of asterisks with 4 rows, where row i has i stars.问题:打印一个 4 行的星号直角三角形,第 i 行有 i 个星号。

FOR i FROM 1 TO 4:
    SET line TO ""
    FOR j FROM 1 TO i:
        SET line TO line + "*"
    OUTPUT line

The outer loop variable i controls which row we are on and, crucially, also controls how many times the inner loop runs; this is the key difference from the 3×3 multiplication table, where both loops always ran a fixed number of times. Here the inner loop's bound (i) changes every outer iteration.外层循环变量 i 既控制当前是第几行,又(关键地)控制内层循环运行的次数,这正是与 3×3 乘法表的关键区别:后者两层循环的次数都固定。此处内层循环的边界(i)在每次外层迭代中都会变化。

for i in range(1, 5):
    line = ""
    for j in range(1, i + 1):
        line += "*"
    print(line)

Output: a single *, then **, then ***, then ****: four rows of growing width. Building the string with a per-row accumulator (line) inside the outer loop, then printing it once the inner loop finishes, is the standard way to construct one line of output character by character.输出:单个 *,然后 **,然后 ***,然后 ****,四行宽度递增。在外层循环内用逐行累加器(line)构建字符串,待内层循环结束后再打印一次,是逐字符构造一行输出的标准做法。

Exam tip考试提示

Command words: trace, state the output and how many times. Use a table with a column for i and a column for j, and write every inner pass for each outer value. Fixed bounds multiply (4 × 5 = 20); when the inner bound is the outer variable, add the counts instead (1 + 2 + 3 + 4 = 10). Common errors: using the same variable name in both loops, and stopping the trace before the inner loop has finished.

指令词:追踪、写出输出和共多少次。用一张表,i 一列、j 一列,并为每个外层的值写出每一次内层循环。边界固定时相乘(4 × 5 = 20);内层边界是外层变量时,则把各次的次数相加(1 + 2 + 3 + 4 = 10)。常见错误:两个循环使用同一个变量名,以及在内层循环尚未结束时就停止追踪。

Check your understanding自我检测
A grid is printed with 6 rows and 4 columns by nested loops with fixed bounds. How many times does the inner body run?用边界固定的嵌套循环打印一个 6 行 4 列的网格。内层循环体共运行多少次?

6 × 4 = 24 times: each of the 6 outer passes runs the inner body 4 times.

6 × 4 = 24 次:6 次外层循环中,每次都让内层循环体运行 4 次。

Worked Example 14 prints a triangle with 4 rows. How many stars does a triangle with 5 rows contain, and why is it not 5 × 5?例题 14 打印 4 行的三角形。5 行的三角形共有多少颗星?为什么不是 5 × 5?

Row i has i stars, so the total is 1 + 2 + 3 + 4 + 5 = 15. The inner bound is i, which changes with each outer pass, so the counts are added rather than multiplied.

第 i 行有 i 颗星,所以总数是 1 + 2 + 3 + 4 + 5 = 15。内层边界是 i,随每次外层循环而变化,所以各次的次数要相加而不是相乘。

Trace for i in range(3): containing for j in range(i): with print(i, j). List the output.追踪 for i in range(3):,其内含 for j in range(i):,循环体为 print(i, j)。列出输出。

1 0, 2 0, 2 1. For i = 0, range(0) is empty, so nothing prints; for i = 1, j is 0 only; for i = 2, j is 0 then 1. That is 0 + 1 + 2 = 3 lines.

1 0、2 0、2 1。i = 0 时 range(0) 为空,不输出任何内容;i = 1 时 j 只有 0;i = 2 时 j 依次为 0、1。共 0 + 1 + 2 = 3 行。


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

Control flow questions in school assessments typically ask you to trace code, write pseudocode, or justify a choice. The tactics below cover the three most common sources of error.学校的控制流程题通常要求你追踪代码、编写伪代码或论证某个选择。以下策略涵盖三种最常见的出错来源。

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 that state the reason are a complete justification.若被问"为何选 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 still shows where the logic went wrong. "I calculated it mentally" leaves nothing to check.列标题 = 变量名;行 = 步骤。到达错误处的部分追踪,也能显示逻辑在哪里出错。"我在脑中计算了"则没有任何可检查的内容。
  • 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, so you 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(原文):"编写具有嵌套结构的算法(如计算数组元素、求总和、查找最大/最小值或执行线性搜索)。"
ICS3U A2.3 requires nested structures; recursion, OOP and file I/O are ICS4U topics in the Ontario extract.ICS3U A2.3 要求嵌套结构;递归、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.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, so 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 课程之前掌握全部七节,可消除前几周最陡峭的学习曲线。

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 a while loop and a for loop?while 循环和 for 循环有什么区别?

A for loop repeats a fixed, known number of times, typically iterating over a sequence, while a while loop repeats as long as a condition stays True. Use a for loop when you know the count and a while loop when you do not.for 循环重复固定的、已知的次数,通常用于遍历一个序列;while 循环则在条件保持为 True 时一直重复。次数已知时用 for,未知时用 while。

What is the difference between break and continue?break 和 continue 有什么区别?

break immediately exits the innermost loop and the program continues after it, while continue skips the rest of the current iteration and jumps back to the loop's condition check. Use break when you have found what you need and continue to skip items that fail a filter.break 立即退出最内层循环,程序从循环之后继续执行;continue 跳过当前这一轮剩余的代码,回到循环的条件判断。找到所需内容时用 break,跳过不符合筛选条件的项时用 continue。

What causes an infinite loop and how do I avoid it?什么会导致死循环,如何避免?

An infinite loop happens when a while loop's condition never becomes False, so the program runs forever. The most common cause is forgetting to update the variable the condition depends on inside the loop body.当 while 循环的条件永远不变为 False 时就会出现死循环,程序会一直运行。最常见的原因是忘记在循环体内更新条件所依赖的变量。

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

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.8CSTA 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.3ICS3U 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" ContentBC 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.2CSE1120 结果 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 are the hardest to trace, so give them extra practice.对于你编写的每个循环(loop,循环)或条件语句,问自己:哪种结构最合适,为什么?CSTA 3A-AP-15 要求你从可读性和性能角度论证控制结构的选择。用变量表追踪每个循环示例。掌握嵌套结构(nested,嵌套)(§3 和 §7):它们最难追踪,值得多做练习。