Python Function to Calculate Average of List Using For Loop
Here's a Python function that computes and prints the average value of a list of numbers using a for loop:
def compute_average(numbers):
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print('The average is:', average)
return average
You can call this function by passing a list of numbers as the argument, like this:
numbers_list = [1, 2, 3, 4, 5]
average = compute_average(numbers_list)
This will compute the average of the numbers in the list and print 'The average is: 3.0' to the console. The average value will also be returned by the function and stored in the average variable.
原文地址: https://www.cveoy.top/t/topic/pdeM 著作权归作者所有。请勿转载和采集!