Totalling & counting · 合計とカウント
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.
合計: 累積和
- 合計化は一連の数字を足し合わせます。
totalを0から始め、その都度値を加えていきます。- このパターン
total = total + valueは**蓄積器(accumulator)**と呼ばれます。
nums = [10, 20, 30]
total = 0
for n in nums:
total = total + n
print(total) # 60
Building a running total · 累積和の作成
Totalling — start at 0, then add each value as the loop visits it. · 合計 — 0から始め、ループが各値を通過するたびに追加します。
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.
カウント: 累計
- カウントは、特定のルールに合致する値がいくつあるかを数えます。
countを0から始め、ルールが真であるたびに1を加えていきます。
nums = [4, -2, 7, -5]
count = 0
for n in nums:
if n > 0:
count = count + 1
print(count) # 2
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.
平均 = 合計 ÷ 件数
- 平均は、合計を値の個数で割ったものです。
len(nums)はリスト内のアイテム数を返します。
nums = [2, 4, 6]
average = sum(nums) / len(nums)
print(average) # 4.0
In the exam: standard methods
- Totalling and counting are named standard methods in the syllabus.
試験対策: 標準的な手法
- 合計化とカウントは、カリキュラムにおける標準手法として定義されています。
Total ← 0
FOR I ← 1 TO 5
Total ← Total + Number[I]
NEXT I
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ずつ増やします。 - ループ内で合計をリセットしないでください。
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. · 実行ボタンをクリックして出力を確認してください。