此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
用迭代来重复
- 迭代(iteration)是指一遍又一遍地做同样的步骤。
- 循环让你不用把同一行代码写很多次。
- AP CSP 重视循环,因为它们让一点点代码就能完成大量工作。
用 for 和 range 计数
for i in range(n):把循环体重复n次。range(5)给出0, 1, 2, 3, 4(在 5 之前停止)。- 循环体要缩进,就像
if一样。
English
for i in range(5):
print(i)
累加出一个总和(accumulation)
- 累加器(accumulator)是在循环里不断变大的变量。
- 在循环之前把它从
0开始。 - 每一轮往里加,累出一个运行中的总和。
English
total = 0
for n in range(1, 6):
total = total + n
print(total)
用 while 循环直到某个条件
while循环只要条件为True就一直重复。- 循环里必须有东西朝着让条件变成
False的方向走。 - 当你事先不知道次数时使用它。
English
count = 3
while count > 0:
print(count)
count = count - 1
遍历一个列表(for-each)
for item in mylist:依次访问每个元素。- 循环变量每一轮保存一个元素。
- 这是处理每个值的简洁方法。
English
scores = [10, 20, 30]
for s in scores:
print(s)
在 AP CSP 伪代码中
- CB 有三种循环形式,与 Python 的循环相对应。
REPEAT n TIMES= 固定次数;REPEAT UNTIL(cond)= 循环直到条件为真。FOR EACH x IN list= 逐项循环。DISPLAY= print,←==,MOD=%。
REPEAT 5 TIMES
{
DISPLAY("hi")
}
count ← 3
REPEAT UNTIL (count = 0)
{
DISPLAY(count)
count ← count - 1
}
FOR EACH s IN scores
{
DISPLAY(s)
}
常见错误
range(n)从0到n - 1。- 在
while里改动条件,否则它永不停止。
现在轮到你
- 在每个任务里使用一个循环。
- 按检查答案来测试你的代码。
探索
Iteration repeats the body
A loop repeats; a 反例 and a 总 change each pass.
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Use a for loop with range(...) to add the whole numbers 1 through 10. Store the result in total. (It should be 55.)
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
Use a while loop to print the numbers 5, 4, 3, 2, 1, each on its own line, then print Go. Start from n = 5.
点击“运行”查看此处输出。
难度 2/5 · 今日首次完成可获 140 金币及少量额外奖励
nums is(是) [3, 6, 7, 8, 10, 11]. Loop over it with a for-each loop and count how many values are 等线 (use % 2 == 0). Store the count in evens. (It should be 3.)
点击“运行”查看此处输出。