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 实现,代码块后附中文说明。
Boolean Conditions & Comparison布尔条件与比较
- Evaluate comparison expressions and compound Boolean expressions built with
and,orandnotfor given values. - Apply the precedence order
not, thenand, thenor, 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),并用括号明确想要的分组。 - 区分赋值(
=)与比较(==),并说明条件中需要哪一个。
==equal to 等于!=not equal to不等于<less than 小于>greater than大于<=less than or equal 小于等于>=greater than or equal大于等于
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:非会员被错误地给了折扣。括号让预期的分组一目了然,而且没有任何代价。
True when x = 4?当 x = 4 时,哪个表达式的值为 True?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)。not (x > 3) equal when x = 5?当 x = 5 时,not (x > 3) 等于什么?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 执行。只写最终结果而不展示过程,是不完整的答案。
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
- Write an
if/elif/elsechain 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
elifchain from a series of separateifstatements.
- 用伪代码和 Python 编写包含三个或更多分支的
if/elif/else链。 - 安排条件的顺序,使第一个为 True 的分支恰好是正确的分支,并解释为什么只有一个分支运行。
- 用边界值(例如 17、18 和 65)测试条件链,并区分
elif链与一连串独立的if语句。
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 为嵌套条件。
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。应把测试按范围从窄到宽排列,并在每次改动后重新测试边界年龄。
score = 75 in the grade classifier above, which branch executes?在上面的等级分类中,score = 75 时哪个分支执行?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 IFCommand 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 语句,导致两个分支都运行。
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嵌套条件
- Write a nested conditional (an
ifinside anif) 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
elseto itsifby indentation. - Rewrite a nested conditional as a flatter chain with
and/elifand check that both versions give the same results.
- 用伪代码和 Python 编写嵌套条件(
if内嵌if),并追踪给定输入下哪个分支运行。 - 解释外层条件为 False 时为何跳过内层块,并通过缩进把每个
else与其对应的if配对。 - 把嵌套条件改写成更扁平的
and/elif形式,并检查两个版本结果相同。
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 要求"嵌套结构"。
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。若每一层都需要各自的提示信息,就保留嵌套形式;若只关心最终结果,就用扁平形式。
age = 10 and height = 150?在主题乐园例题中,当 age = 10、height = 150 时,输出是什么?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 配对。
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 循环
- Trace a
whileloop 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 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 命名"迭代(重复)"。
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 的简写(减法赋值运算符)。
SET x TO 1WHILE x < 4: SET x TO x + 1这个循环的循环体执行多少次?SET x TO 1WHILE x < 4: SET x TO x + 1infinite loop,无限循环)。程序永远不会退出循环体。常见原因:忘记更新条件所依赖的变量。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,这会在首次输入有效时反而要求重新输入,而首次输入无效时直接放行)。始终自问:"循环在什么条件为真时持续运行?",此处是当数值仍然无效时。
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 的循环会运行零次。
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 循环
- Write a
forloop overrange(start, stop)or over a list, and list the values the loop variable takes. - Compute the number of iterations of
range(start, stop)asstop - start, and choosen + 1to include n. - Apply the running-total and running-maximum or minimum patterns, and choose between
forandwhilefor a given task.
- 编写遍历
range(start, stop)或列表的for循环,并列出循环变量依次取到的值。 - 把
range(start, stop)的迭代次数算成stop - start,并用n + 1来包含 n。 - 应用累计总和与滚动最大值或最小值的模式,并为给定任务在
for与while之间做出选择。
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(差一陷阱)。
for i in range(3, 7) print when you print i each iteration?for i in range(3, 7) 每次迭代打印 i,会打印什么?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)。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)即可用同一模式求最小值。
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。
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
- Choose between
break(leave the loop) andcontinue(skip to the next pass) for a given task. - Trace a loop that uses
breakorcontinue, including one inside a nested loop, and state the output. - Place the update of a
whileloop variable so thatcontinuecannot skip it and cause an infinite loop.
- 针对给定任务,在
break(离开循环)与continue(跳到下一轮)之间做出选择。 - 追踪使用
break或continue的循环(包括嵌套循环中的情形)并写出输出。 - 合理放置
while循环变量的更新位置,使continue不会跳过它而造成无限循环。
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,继续)。用于跳过不满足过滤条件的项目。
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(每行一对):外层循环仍然完整运行三次。
break do when executed inside a loop?break 在循环内部执行时会做什么?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(中断)立即退出最内层循环。执行继续循环后的第一条语句。它不会结束程序或重新开始循环。continue do when executed inside a loop?continue 在循环内部执行时会做什么?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 循环)。它不会退出循环。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 之后。
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嵌套循环
- Write nested
forloops 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 的表格追踪它们。 - 计算内层循环体的总执行次数:两个边界都固定时用乘法,内层边界取决于外层变量时用加法。
- 在外层循环内使用逐行累加器来构造一行输出。
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 要求嵌套结构。
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
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)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)构建字符串,待内层循环结束后再打印一次,是逐字符构造一行输出的标准做法。
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)。常见错误:两个循环使用同一个变量名,以及在内层循环尚未结束时就停止追踪。
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.学校的控制流程题通常要求你追踪代码、编写伪代码或论证某个选择。以下策略涵盖三种最常见的出错来源。
- 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 = 未知次数、条件依赖。两句话说明原因,就是一份完整的论证。
- Assignment vs comparison.赋值与比较。
x = 5sets;x == 5tests. 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。
- 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,嵌套循环)作为合理性检查。那个乘积就是"循环体运行多少次?"的答案。
- 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闪卡
Practice Quiz综合测验
if 7 >= 7: print("yes") else: print("no")?if 7 >= 7: print("yes") else: print("no") 的输出是什么?x = 0; while x < 3: x += 1. What is x when the loop ends?追踪:x = 0; while x < 3: x += 1。循环结束时 x 是多少?for i in range(0, 5): print(i) print?for i in range(0, 5): print(i) 打印什么?Readiness Checklist准备就绪清单
Tick each item when you can do it cold, without notes, on a first attempt.能在无笔记、首次尝试下完成,再勾选每一项。
- Evaluate any boolean expression with comparison and logical operators (==, !=, <, >, <=, >=, and, or, not) and state whether it is True or False. Distinguish x = 5 (assignment) from x == 5 (comparison). 🇺🇸 AP CSP 3.5 / 🇨🇦 AB CSE1120用比较和逻辑运算符(==、!=、<、>、<=、>=、and、or、not)求值任意布尔表达式,并说明其为 True 还是 False。区分 x = 5(赋值)和 x == 5(比较)。🇺🇸 AP CSP 3.5 / 🇨🇦 AB CSE1120
- Write a complete if/elif/else selection in pseudocode and Python for a problem with at least three branches (e.g., grade classifier). Trace it with a value that hits each branch. 🇨🇦 ON ICS3U A2.2 / AP CSP 3.6为至少三个分支的问题(如等级分类器)用伪代码和 Python 写出完整的 if/elif/else 选择结构。用触及每个分支的值追踪它。🇨🇦 ON ICS3U A2.2 / AP CSP 3.6
- Write and trace a nested conditional (if inside if). Explain why the inner block does not run when the outer condition is False. 🇨🇦 AB CSE1120 2.8.1 / AP CSP 3.7写出并追踪嵌套条件(if 内嵌 if)。解释为何外层条件为 False 时内层块不运行。🇨🇦 AB CSE1120 2.8.1 / AP CSP 3.7
- Write a while loop that counts, accumulates, or searches. Identify what variable must be updated inside the body to prevent an infinite loop. Trace the loop with a variable table. 🇨🇦 ON ICS3U A2.2 / AB CSE1120 outcome 1写一个用于计数、累加或搜索的 while 循环。找出必须在循环体内更新哪个变量以防止无限循环。用变量表追踪循环。🇨🇦 ON ICS3U A2.2 / AB CSE1120 结果 1
- Write a for loop using range(). Compute range(1, n+1) and explain why n+1 is needed to include n. State the number of iterations for any given range. 🇨🇦 BC CP11 / AP CSP 3.8用 range() 写 for 循环。计算 range(1, n+1) 并解释为何需要 n+1 才能包含 n。说明任意给定范围的迭代次数。🇨🇦 BC CP11 / AP CSP 3.8
- Explain the difference between break (exits loop) and continue (skips to next iteration). Write one example of each and trace through one full iteration showing the effect. 🇨🇦 AB CSE1120 outcome 2.8解释 break(退出循环)和 continue(跳到下一次迭代)的区别。各写一个示例,并追踪一次完整迭代以显示效果。🇨🇦 AB CSE1120 结果 2.8
- Write a nested loop (e.g., multiplication table). Compute the total iterations (outer × inner). Trace one full outer iteration manually showing all inner iterations. 🇨🇦 AB CSE1120 2.8.2 / ON ICS3U A2.3写一个嵌套循环(如乘法表)。计算总迭代次数(外层 × 内层)。手工追踪一次完整的外层迭代,展示所有内层迭代。🇨🇦 AB CSE1120 2.8.2 / ON ICS3U A2.3
- Justify choosing for vs while for a given problem scenario in one or two sentences, citing readability and/or the known-vs-unknown iteration count. 🇺🇸 CSTA 3A-AP-15用一两句话为给定问题场景论证选择 for 还是 while,引用可读性和/或已知与未知迭代次数。🇺🇸 CSTA 3A-AP-15
- Identify an off-by-one error in a given loop: spot whether < should be <= (or vice versa), state the incorrect output vs the expected output, and write the fix. 🇨🇦 BC CP11 / AB CSE1120识别给定循环中的差一错误:判断 < 是否应改为 <=(或反之),说明错误输出与预期输出,并写出修复。🇨🇦 BC CP11 / AB CSE1120
- State verbatim the CSTA standard 3A-AP-15 and the Ontario ICS3U expectation A2.2, and identify which topic of this guide each one maps to. 🇺🇸 CSTA / 🇨🇦 ON逐字陈述 CSTA 标准 3A-AP-15 和安大略 ICS3U 期望 A2.2,并找出本指南中各自对应的主题。🇺🇸 CSTA / 🇨🇦 ON
- Write a complete program combining if/elif/else inside a for or while loop (e.g., iterate a list, classify each item, accumulate counts). Trace it with two input values. 🇨🇦 ON ICS3U A2.3 / AB CSE1120写一个完整程序,将 if/elif/else 嵌套在 for 或 while 循环内(如遍历列表、对每项分类、累计计数)。用两个输入值追踪它。🇨🇦 ON ICS3U A2.3 / AB CSE1120
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 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 |
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(计数控制)的区别。读每个速记框。在继续之前用具体值追踪伪代码示例。
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):它们最难追踪,值得多做练习。