Iteration
Python for AP CS Principles Lesson 7 2:11 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Iteration means doing the same steps again and again, which is how a little code does a lot of work.
迭代的意思是把同样的步骤一遍遍地做, 这也正是很少的代码能干很多活的原因。
The commonest loop counts with range.
最常见的循环用 range 来计数。
And here is the off-by-one everybody meets: range of five does not give you a five.
而下面这个"差一"错误人人都会碰到: range(5) 并不会给你一个 5。
It stops before five.
它在 5 之前就停了。
Look at the cells — zero, one, two, three, four, and then an empty slot.
看那几个格子——0、1、2、3、4,然后是一个空位。
Five values, so the body runs exactly five times.
一共五个值,所以循环体正好跑五次。
A very common job is building a running total.
一件非常常见的活儿,是把一个总数累加起来。
The variable that grows is called an accumulator, and you add to it each pass: one, three, six, ten, fifteen.
那个不断变大的变量叫"累加器", 每一轮你都往它上面加:1、3、6、10、15。
Watch the box climb.
看那个盒子往上爬。
The line that matters most is the boring one at the top — set the accumulator to zero before the loop.
最要紧的一行反而是最不起眼的那一行—— 在循环之前把累加器置为 0。
Leave that out and there is nothing to add to.
漏了它,就没有东西可加了。
Sometimes you do not know the count in advance, and that is what a while loop is for.
有时候你事先并不知道要循环多少次, while 循环就是干这个的。
It repeats as long as it is True.
只要条件为真,它就一直重复。
Count starts at three, so it prints three, two, one and stops.
count 从 3 开始,所以它打印 3、2、1,然后停下。
But look at that last line closely — something inside the loop has to move the condition towards False.
但仔细看最后那一行—— 循环体里必须有东西把条件往"假"的方向推。
Take it away and the loop never stops.
把它拿掉,这个循环就永远停不下来。
The exam has three loop shapes and they match the three you just wrote.
考卷上有三种循环写法,正好对上你刚写的这三种。
REPEAT n TIMES is a fixed count.
REPEAT n TIMES 是固定次数。
FOR EACH x IN a list is the for-each.
FOR EACH x IN 一个列表,就是 for-each。
And the middle one needs care: Python loops WHILE the test is true, but the exam writes REPEAT UNTIL, so it repeats until it is.
而中间那一种要小心: Python 是"当"条件为真时循环, 但考卷写的是 REPEAT UNTIL,也就是重复"直到"条件为真。
Same loop, opposite wording.
同一个循环,说法正好相反。
Four things to take with you.
带走四点。
One: a loop lets a little code do a lot of work.
第一:循环让很少的代码干很多活。
Two: range starts at zero and stops before the number you give it.
第二:range 从 0 开始,并且在你给的那个数之前就停。
Three: set an accumulator to zero before the loop starts.
第三:在循环开始之前把累加器置为 0。
Four: a while loop needs something that ends it.
第四:while 循环需要有东西让它结束。
Now write some loops in the tasks below.
现在去下面的题里写几个循环。