Accumulators

Accumulators

An accumulator is a variable that collects a result across the passes of a loop. Create it before the loop, update it inside, use it after:

def total_cost(prices):
    total = 0
    for price in prices:
        total = total + price
    return total

print(total_cost([12, 30, 8]))

Output:

50

total starts at 0 and grows by one price per pass: 0, 12, 42, 50.

total = total + price is common enough to have a short form: total += price. The same works for other operators: -=, *=.

Counting is the same pattern with += 1 inside an if:

def count_cheap(prices):
    count = 0
    for price in prices:
        if price < 10:
            count += 1
    return count

Exercise

  1. Define a function named count_passing with one parameter, scores (a list of numbers).
  2. It returns how many scores are 60 or higher. Use an accumulator.

count_passing([80, 45, 60, 92]) returns 3.

Run your code to see the output, then press Submit.

Tests

import unittest


class TestCountPassing(unittest.TestCase):
    def test_three_of_four_pass(self):
        self.assertEqual(count_passing([80, 45, 60, 92]), 3)

    def test_exactly_60_passes(self):
        self.assertEqual(count_passing([60]), 1)

    def test_59_fails(self):
        self.assertEqual(count_passing([59]), 0)

    def test_empty_list_gives_zero(self):
        self.assertEqual(count_passing([]), 0)
def count_passing(scores):
    count = 0
    for score in scores:
        if score >= 60:
            count += 1
    return count


print(count_passing([80, 45, 60, 92]))
Solution hidden. Give it a real try first.

Sign in to join the discussion.

No comments yet. Be the first to ask a question.

main.py
Console
Press Run to execute your code, or Submit to test and complete this problem.