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. · اضغط تشغيل لرؤية المخرجات هنا.