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เรียกว่า ตัวสะสม
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.
ลองดูเลย
- ใช้ลูปที่มีผลรวมสะสมหรือจำนวนสะสม
- กด Check answer เพื่อทดสอบโค้ดของคุณ
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
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. · คลิก Run เพื่อดูผลลัพธ์ที่นี่