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!

Asked By: FriendlyChemist

||

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]))
Answered By: Flow
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.