Iteration — loops · 迭代 —— 循环
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version. · 此页面需较新浏览器(支持 SharedArrayBuffer)。请升级 Chrome、Edge、Firefox 或 Safari 至最新版本。
English
Count-controlled loops
- Iteration means repeating steps.
- A count-controlled loop repeats a fixed number of times.
- In Python that is
for i in range(n):.
中文
计数控制循环
- 迭代(iteration)就是重复一些步骤。
- 计数控制(count-controlled)循环重复固定的次数。
- 在 Python 里就是
for i in range(n):。
for i in range(5):
print("Hello")
English
Choosing the range
range(5)gives0, 1, 2, 3, 4.range(1, 6)gives1, 2, 3, 4, 5— it stops before 6.range(2, 11, 2)counts in steps of 2.
中文
选择范围
range(5)给出0, 1, 2, 3, 4。range(1, 6)给出1, 2, 3, 4, 5—— 在 6 之前停下。range(2, 11, 2)以 2 为步长计数。
for n in range(1, 6):
print(n)
English
Pre-condition loops: while
- A pre-condition loop tests before each pass.
- It may run zero times if the test is false at the start.
中文
前测循环:while
- 前测(pre-condition)循环在每一轮之前测试。
- 如果一开始测试就为假,它可能一次都不运行。
count = 0
while count < 5:
print(count)
count = count + 1
English
Post-condition loops: REPEAT UNTIL
- A post-condition loop tests after each pass, so it always runs at least once.
- Python has no
repeat, so we usewhile Truewithbreak.
中文
后测循环:REPEAT UNTIL
- 后测(post-condition)循环在每一轮之后测试,所以至少运行一次。
- Python 没有
repeat,所以我们用while True加break。
total = 0
while True:
total = total + 1
if total >= 3:
break
print(total)
Explore · 探索
Each pass changes count · 每一轮改变 count
A loop repeats its body; count must change so the test finally fails. · 循环重复执行循环体;count 必须改变,测试才会最终为假。
English
In the exam: FOR, WHILE, REPEAT
- Pseudocode has all three loop types.
中文
在考试里:FOR、WHILE、REPEAT
- 伪代码有这三种循环类型。
FOR I ← 1 TO 5
OUTPUT I
NEXT I
English
Common mistakes
- A
forloop repeats a known number of times; awhilerepeats until something changes. range(n)runs0ton - 1.- Change the condition inside a
while, or it never ends.
中文
常见错误
for循环重复已知的次数;while一直重复,直到某个值改变。range(n)从0到n - 1。- 在
while里改动条件,否则它永不结束。
English
Now you try
- Pick the loop that fits each task.
- Press Check answer to test your code.
中文
现在轮到你
- 为每个任务选择合适的循环。
- 按检查答案来测试你的代码。
Use a for loop to print the numbers 1 to · 到 5, one on each line. · 用 for 循环打印数字 1 到 5,每行一个。
Click Run to see the output here. · 点击“运行”查看此处输出。
Use a loop to add up the numbers 1 to · 到 10, then print the total (it is 55). · 用循环把 1 到 10 加起来,然后打印总和(是 55)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Read a whole number n, then count down · 下 from n to · 到 1, one per line. For input 3, print 3, 2, 1. · 读取一个整数 n,然后从 n 倒数到 1,每行一个。当输入为 3 时,打印 3、2、1。
Click Run to see the output here. · 点击“运行”查看此处输出。