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. · לחץ על הרץ כדי לראות את התוצא כאן.