Lặp lại
Python cho IGCSE Tin học Bài học 4 2:19 Thuyết minh tiếng Anh · Có thể chuyển đổi phụ đề tiếng Anh và tiếng Trung
Chương
Biên bản ghi âm
Write the same line ten times and the eleventh will break you.
同一行写十遍,写到第十一遍你就受不了了。
That is what a loop is for.
循环就是干这个用的。
Iteration means repeating steps, and the everyday loop is the one that repeats a fixed number of times.
迭代就是重复执行步骤,而最常见的循环,是重复固定次数的那一种。
In Python that is for i in range.
在 Python 里就是 for i in range。
Range on its own counts from nought.
只给一个数字,range 从 0 开始数。
Give it two numbers and it will start at one, or wherever you say.
给两个数字,它就可以从 1 开始,或者从你说的任何地方开始。
Give it three and it counts in twos.
给三个数字,它就会隔一个数一次。
But here is the catch, and it differs from the exam: range stops BEFORE the number you give it, so you write six to get five.
但这里有个要注意的地方,而且和考卷不同: range 在你给的那个数字之前就停了, 所以你要写 6 才能数到 5。
The syllabus names three kinds of loop and asks you to tell them apart.
考纲列出三种循环,并且会让你区分它们。
A FOR loop repeats a number of times you already know.
FOR 循环重复的次数是你事先就知道的。
A WHILE loop tests before each pass.
WHILE 循环在每一轮之前判断。
A REPEAT loop tests after each pass.
REPEAT 循环在每一轮之后判断。
And that placement decides the one fact the exam actually wants: zero times versus at least once.
而判断放在哪里,决定了考试真正想考的那个事实: 可能一次都不跑,还是至少跑一次。
If the test is false at the very start, a while loop never runs its body, and a repeat loop has already run it once.
如果判断一开始就是假的, while 循环的循环体一次都不会执行, 而 repeat 循环已经执行过一次了。
A while loop has a hazard that a for loop does not.
while 循环有一个 for 循环没有的隐患。
Something inside the body has to move the test toward false — here, the counter going up.
循环体里必须有东西让那个判断朝"假"的方向走—— 这里就是那个不断增加的计数器。
Forget that line and the test is true forever, and the program hangs.
漏掉那一行,判断就永远为真,程序就卡住了。
A for loop counts for you; a while loop does not, so you have to move it toward its end yourself.
for 循环替你计数;while 循环不会, 所以你得自己让它走向终点。
Now the lesson's second task, in both notations: add up one to ten.
现在看这一课的第二道题,两种写法并排:把 1 到 10 加起来。
Look at where the total is set to nought.
注意 total 被设为 0 的那一行在哪里。
It is outside the loop, before it starts.
它在循环外面,在循环开始之前。
Put that line inside and the total resets on every single pass, so the answer comes out as ten — the last number, not the sum.
把那一行放进循环里,total 每一轮都会被重置, 于是答案变成 10——最后那个数字,而不是总和。
That is next lesson's whole topic, and it starts here.
这正是下一课的全部主题,而它从这里开始。
Four things to take with you.
带走四点。
One: a FOR loop repeats a known number of times.
第一:FOR 循环重复的次数是已知的。
Two: a WHILE tests first, so it may run zero times.
第二:WHILE 先判断,所以可能一次都不跑。
Three: a REPEAT tests last, so it always runs once.
第三:REPEAT 后判断,所以至少跑一次。
Four: range stops before its end — write six to reach five.
第四:range 在终点之前停下——要数到 5,就写 6。
Now do the three tasks.
现在去做那三道题。
Bình luận
Chưa có bình luận nào. Hãy là người đầu tiên đặt câu hỏi hoặc chia sẻ điều gì đó.