Solution Design Create a variable that holds the sum total of the numbers in the numbers list. Then write a for
loop to go over all the numbers in the list, adding them to this total. This is identical to the
calculateSum()
function in Exercise #13 ―Sum & Product.‖ After the loop, return the total
divided by the amount of numbers in the numbers list. You can use Python’s built-in len()
function for this.
While you shouldn’t use Python’s built-in sum() function, you can import your sumproduct.py program from Exercise #13, ―Sum & Product‖ for its calculateSum() function. After completing
Exercise #13, make sure sumproduct.py is in the same folder as average.py. Then use import
sumproduct
to import the module and sumproduct.calculateSum() to call the function.
Special Cases and Gotchas If the numbers parameter is an empty list, the function should return None. Therefore, you
should put the code that checks this at the start of the function.
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/average-template.py and paste it into your code editor. Replace the underscores with code to make a working program:
def average(numbers):
# Special case: If the numbers list is empty, return None: if len(____) == ____:
return ____
# Start the total at 0: total = ____
# Loop over each number in numbers: for number in ____:
# Add the number to the total: total ____ number
# Get the average by dividing the total by how many numbers there are: return ____ / ____(numbers)
The complete solution for this exercise is given in Appendix A and https://invpy.com/average.py.
You can view each step of this program as it runs under a debugger at https://invpy.com/average-debug/.