Totalling and counting
Python for IGCSE CS Lesson 5 2:07 English narration · English + 中文 subtitles burned in
Chapters
Transcript
Adding up a list of numbers has a name in the syllabus: totalling.
把一列数字加起来,在考纲里有个名字:求和(totalling)。
It works with one extra variable that remembers the answer so far.
它靠一个额外的变量,记住到目前为止的答案。
The total starts at nought, before the loop begins.
total 从 0 开始,在循环开始之前。
Then each pass adds the next one to it — ten, then thirty, then sixty.
然后每一轮把下一个数加进去——10,然后 30,然后 60。
Watch the box change as the loop goes round; that growing value is the whole idea.
看着那个盒子随着循环转动而变化; 那个不断长大的值,就是全部的思想。
That first line is where the marks are lost.
第一行正是丢分的地方。
Total equals nought must sit outside the loop, before it starts.
total = 0 必须写在循环外面,在循环开始之前。
Move it inside and it runs again on every pass, wiping the total each time — so the answer comes out as the last number instead of the sum.
把它移到里面,它每一轮都会重新执行一次,每次都把总和抹掉—— 于是答案变成了最后那个数字,而不是总和。
One line, one indent, completely different result.
一行,一个缩进,结果完全不同。
And the program still runs, which is exactly why it is worth checking.
而且程序照样能跑,这正是它值得检查的原因。
Counting is the same shape with two small changes.
计数是同一个形状,只有两处小改动。
Instead of adding the value, you add one instead — because you are tallying how many, not how much.
不是把值加进去,而是加 1—— 因为你数的是"有多少个",不是"总共多少"。
And there is a test wrapped round the adding, so only the values that pass get counted.
而且加法外面套了一个判断, 所以只有通过判断的值才会被计入。
Start at nought, loop, add: the skeleton has not changed at all.
从 0 开始、循环、累加:骨架一点都没变。
The average is the third one, and it is just the first two together: total them up, then divide by how many there are.
平均值是第三个,而它就是前两个合起来: 先求和,再除以个数。
In Python, len gives that count, so the same code works whatever is in the list.
在 Python 里,len 给出这个个数, 所以不管列表里装的是什么,同一段代码都成立。
And note what the syllabus calls all three of these — the standard methods.
再注意考纲怎么称呼这三件事——标准方法(standard methods)。
Expect that phrase on the paper, and expect to be asked to write one from scratch.
考卷上会出现这个说法, 也会要求你从头写出其中一个。
Four things to take with you.
带走四点。
One: totalling means start at nought, then add each value.
第一:求和就是从 0 开始,然后把每个值加进去。
Two: counting means add one whenever the test passes.
第二:计数就是每当判断通过时加 1。
Three: the average is the total over how many.
第三:平均值是总和除以个数。
Four: set the starting value before the loop, never inside it.
第四:初始值写在循环之前,绝不要写在里面。
Now do the three tasks.
现在去做那三道题。