Have a go at it. The editor and the docs panel are open, and your code is saved as you type. Running it needs a free account — you’ll come back to exactly what you wrote.

Adding Up with a Loop

~8 mincode completion

A for loop runs the same code once for each item in a collection:

for name in ["ada", "grace"]:
    print(name)

The accumulator pattern is the one you will reuse forever: make a variable before the loop, update it inside, use it after.

total = 0
for price in prices:
    total = total + price
return total

total = total + price can be shortened to total += price. They mean exactly the same thing.

Two mistakes worth naming now:

  • Putting total = 0 inside the loop resets it every time, so you end up with only the last value.
  • Putting return total inside the loop exits after the first item.
  • Both are indentation mistakes, and in Python indentation is not decoration, it is the structure.

    Your task:

    Write total_of(numbers) that adds up a list of numbers and returns the total. Write the loop yourself rather than calling the built-in sum. An empty list should return 0.

    Example Tests

    Adds up three numbers

    Input: {"numbers":[1,2,3]}

    Expected: 6

    Negative numbers subtract from the total

    Input: {"numbers":[10,-3,-2]}

    Expected: 5

    An empty list totals 0

    Input: {"numbers":[]}

    Expected: 0

    Python
    def total_of(numbers):
        """
        Add up a list of numbers using a loop.
    
        Args:
            numbers: a list of numbers
    
        Returns:
            Their total. An empty list totals 0.
        """
        # YOUR CODE HERE
        pass

    Run your code to see results

    ⌘↵ runs against the visible tests

    Loading docs…