Python Function to Calculate Average of List Numbers
Here's a Python function that calculates the average value of a given list of numbers, including handling empty lists to prevent division by zero errors:
def compute_average(numbers):
if len(numbers) == 0:
return 0 # Return 0 if the list is empty to avoid division by zero error
total = sum(numbers)
average = total / len(numbers)
print('The average value is:', average)
return average
You can use this function by passing a list of numbers as an argument. For example:
my_list = [1, 2, 3, 4, 5]
compute_average(my_list)
Output:
The average value is: 3.0
This function gracefully handles the scenario where the input list is empty by returning 0, preventing any division by zero errors. This makes it a robust and reliable solution for calculating the average of a list of numbers in Python.
原文地址: https://www.cveoy.top/t/topic/paEG 著作权归作者所有。请勿转载和采集!