Totalling & counting · 累加与计数
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
Totalling: a running total
- Totalling adds up a series of numbers.
- Start a
totalat 0, then add each value to it. - The pattern
total = total + valueis called an accumulator.
中文
累加:一个不断累积的总和
- 累加(totalling)把一连串数字加起来。
- 让
total从 0 开始,然后把每个值加上去。 total = total + value这个模式叫做累加器(accumulator)。
nums = [10, 20, 30]
total = 0
for n in nums:
total = total + n
print(total) # 60
Explore · 探索
Building a running total · 累积一个总和
Totalling — start at 0, then add each value as the loop visits it. · 累加 —— 从 0 开始,循环每访问一个值就加上它。
English
Counting: a running count
- Counting tallies how many values meet a rule.
- Start a
countat 0, then add 1 each time the rule is true.
中文
计数:一个不断累积的数量
- 计数(counting)统计有多少个值符合某条规则。
- 让
count从 0 开始,每当规则为真就加 1。
nums = [4, -2, 7, -5]
count = 0
for n in nums:
if n > 0:
count = count + 1
print(count) # 2
English
Average = total ÷ count
- An average is the total divided by how many values there are.
len(nums)gives the number of items in a list.
中文
平均值 = 总和 ÷ 个数
- 平均值(average)就是总和除以值的个数。
len(nums)给出列表里元素的个数。
nums = [2, 4, 6]
average = sum(nums) / len(nums)
print(average) # 4.0
English
In the exam: standard methods
- Totalling and counting are named standard methods in the syllabus.
中文
在考试里:标准方法
- 累加和计数是考纲里有名字的标准方法(standard methods)。
Total ← 0
FOR I ← 1 TO 5
Total ← Total + Number[I]
NEXT I
English
Common mistakes
- Set the total to
0before the loop, then add to it inside. - A counter starts at
0and goes up by1each time. - Do not reset the total inside the loop.
中文
常见错误
- 在循环之前把总和设为
0,然后在循环内累加。 - 计数器从
0开始,每次加1。 - 不要在循环内重置总和。
English
Now you try
- Use a loop with a running total or count.
- Press Check answer to test your code.
中文
现在轮到你
- 用一个带累加或计数的循环。
- 按检查答案来测试你的代码。
The list nums is set for you. Use a loop to add up every number and store the result in total (the answer is 18). · 列表 nums 已为你设好。用循环把每个数字加起来,把结果存进 total(答案是 18)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Count how many numbers in nums are greater than 0. Store the count in count (the answer is 2). · 统计 nums 中有多少个数字大于 0。把数量存进 count(答案是 2)。
Click Run to see the output here. · 点击“运行”查看此处输出。
Work out the average of the numbers in nums (the total divided by how many there are) and store it in average (the answer is 4.0). · 算出 nums 中数字的平均值(总和除以个数),存进 average(答案是 4.0)。
Click Run to see the output here. · 点击“运行”查看此处输出。