# Exercise #13: Sum & Product

calculateSum([2, 4, 6, 8, 10])   30
calculateProduct([2, 4, 6, 8, 10])   3840 Python’s built-in `sum()` function returns the sum of the list of numbers passed for its argument. In this exercise, you’ll reimplement this behavior for your `calculateSum()` function and also create a `calculateProduct()` function.

Exercise Description

Write two functions named `calculateSum()` and `calculateProduct()`. They both have a parameter named `numbers`, which will be a list of integer or floating-point values. The `calculateSum()` function adds these numbers and returns the sum while the `calculateProduct()` function multiplies these numbers and returns the product. If the list passed to `calculateSum()` is empty, the function returns 0. If the list passed to `calculateProduct()` is empty, the function returns `1`. Since this function replicates Python’s `sum()` function, your solution shouldn’t call.

These Python `assert` statements stop the program if their condition is `False`. Copy them to the bottom of your solution program. Your solution is correct if the following `assert` statements’ conditions are all True:

assert calculateSum([]) == 0

assert calculateSum([2, 4, 6, 8, 10]) == 30

assert calculateProduct([]) == 1

assert calculateProduct([2, 4, 6, 8, 10]) == 3840

Try to write a solution based on the information in this description. If you still have trouble solving this exercise, read the Solution Design and Special Cases and Gotchas sections for additional hints.

Prerequisite concepts: lists, indexes, `for` loops, augmented assignment operator

Solution Design

For calculating a sum in `calculateSum()`, create a variable named `result` to store the running sum result. This variable starts at `0`, and while the program loops over each number in the numbers parameter, each number is added to this running sum. The same is done in `calculateProduct()`, except the `result` variable starts at 1 and is multiplied by each number.

Special Cases and Gotchas

You might be tempted to use a variable named `sum` to store the running sum. However, in Python this name is already used for the built-in `sum()` function. Reusing this name for a local variable means we’d lose the ability to call the original sum() function for the rest of the function’s code because we have overwritten `sum` to the value we put in it rather than Python’s `sum()` function. You want to avoid reusing the names of Python’s built-in functions by overwriting them, as it could cause odd bugs in your code. Some commonly overwritten Python names are `all`, `any`, date, `email`, file, `format`, hash, `id`, `input`, `list`, `min`, max, `object`, open, `random`, set, `str`, `sum`, `test`, and `type`. Don’t use these names for your own variables.

Also, the sum of an empty list of numbers should be 0. The product of an empty list of numbers should be 1. When calculating the product of several numbers, begin the running product result at `1` and not 0. If you start it at `0`, all multiplications result in `0` and your calculateProduct() function will return 0 every time. In mathematics, the numbers 0 and 1 are called the additive identity and multiplicative identity, respectively. Adding the additive identity (0) to a number results in that same number, while multiplying the multiplicative identity (1) with a number results in that same number. For example, 12 + 0 is just 12 and 12 × 1 is just 12 too.

Now try to write a solution based on the information in the previous sections. If you still have trouble solving this exercise, read the Solution Template section for additional hints.

Solution Template

Try to first write a solution from scratch. But if you have difficulty, you can use the following partial program as a starting place. Copy the following code from https://invpy.com/sumproduct-template.py and paste it into your code editor. Replace the underscores with code to make a working program:

def calculateSum(numbers):

# Start the sum result at 0:

result = ____

# Loop over all the numbers in the numbers parameter, and add them

# to the running sum result:

for number in ____:

result += ____

# Return the final sum result:

return ____

def calculateProduct(numbers):

# Start the product result at 1:

result = ____

# Loop over all the numbers in the numbers parameter, and multiply

# them by the running product result:

for number in ____:

result ____ number

# Return the final product result:

return ____

The complete solution for this exercise is given in Appendix A and https://invpy.com/sumproduct.py. You can view each step of this program as it runs under a debugger at https://invpy.com/sumproduct-debug/.

Just like in Exercise #12 “Smallest & Biggest” we can generate a list of one million numbers, and then calculate the sum and product of these numbers. Multiplying one million numbers creates an astronomically large number, so we’ll limit our test to a mere ten thousand numbers. Write the following program and save it in a file named testsumproduct.py. Run it from the same folder as your sumproduct.py file so that it can import it as a module:

import random, smallest

numbers = []

for i in range(10000):

numbers.append(random.randint(1, 1000000000))

print('Numbers:', numbers)

print('Smallest number is', smallest.getSmallest(numbers))

When run, this program displays the million numbers between 1 and 1,000,000,000 it generated, along with the smallest number in that list.