Python Function to Calculate Average of Numbers in a List
Here's a Python function that utilizes a for loop to calculate the average value of numbers within a list:
def compute_average(numbers):
total = 0
count = 0
for num in numbers:
# Check if the current element is a number
if isinstance(num, (int, float)):
total += num
count += 1
if count > 0:
average = total / count
print('The average value is:', average)
return average
else:
print('The list doesn't contain any numbers.')
return None
This function takes a list of numbers as input and initializes two variables: total to track the sum of numbers and count to track the number of valid numbers in the list.
The for loop iterates through each element in the list. Inside the loop, it checks if the current element is a number using the isinstance() function. If it is a number, the current element is added to the total and the count is incremented.
After the loop, it checks if count is greater than 0. If so, it calculates the average by dividing the total by count and assigns it to the average variable. Then, it prints the average value and returns it. If count is 0, it prints a message indicating the list doesn't contain any numbers and returns None.
Here's an example of how to use the function:
numbers = [1, 2, 3, 4, 5]
average = compute_average(numbers)
Output:
The average value is: 3.0
In this example, the average value of the numbers [1, 2, 3, 4, 5] is 3.0.
原文地址: https://www.cveoy.top/t/topic/pdeB 著作权归作者所有。请勿转载和采集!