Averaging numbers in python
Question:
I am struggling to write a function that accurately calculates the average of a list of numbers. I have been working on this for the past day and my code does not seem to be giving the correct answer. I have included my code below.
def average(nums):
total = 0
for num in nums:
total = num + total
average = total / len(nums)
print(average)
average([1, 2, 3, 4, 5])
Thank you all in advance!
Answers:
Using sum
the builtin is faster but other than that you are calculating the average fine.
def average(nums):
total = sum(nums)
average = total / len(nums)
return average
print(average([1, 2, 3, 4, 5]))
I am struggling to write a function that accurately calculates the average of a list of numbers. I have been working on this for the past day and my code does not seem to be giving the correct answer. I have included my code below.
def average(nums):
total = 0
for num in nums:
total = num + total
average = total / len(nums)
print(average)
average([1, 2, 3, 4, 5])
Thank you all in advance!
Using sum
the builtin is faster but other than that you are calculating the average fine.
def average(nums):
total = sum(nums)
average = total / len(nums)
return average
print(average([1, 2, 3, 4, 5]))