Python
Programming Exercises, Gently Explained
139
def calculateProduct(numbers):
# Start the product result at 1:
result = 1
# Loop over all the numbers in the numbers parameter, and multiply
# them by the running product result:
for number in numbers:
result *= number
# Return the final product result:
return result
Exercise #14: Average
def average(numbers):
# Special case: If the numbers list is empty, return None:
if len(numbers) == 0:
return None
# Start the total at 0:
total = 0
# Loop over each number in numbers:
for number in numbers:
# Add the number to the total:
total += number
# Get the average by dividing the total by how many numbers there are:
return total / len(numbers)
Dostları ilə paylaş: