For Python 3.8+, use statistics.fmean for numerical stability with floats. (Fast.)
For Python 3.4+, use statistics.mean for numerical stability with floats. (Slower.)
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
For older versions of Python 3, use
sum(xs) / len(xs)
For Python 2, convert len to a float to get float division:
sum(xs) / float(len(xs))
Answer from Herms on Stack OverflowFor Python 3.8+, use statistics.fmean for numerical stability with floats. (Fast.)
For Python 3.4+, use statistics.mean for numerical stability with floats. (Slower.)
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
import statistics
statistics.mean(xs) # = 20.11111111111111
For older versions of Python 3, use
sum(xs) / len(xs)
For Python 2, convert len to a float to get float division:
sum(xs) / float(len(xs))
xs = [15, 18, 2, 36, 12, 78, 5, 6, 9]
sum(xs) / len(xs)
with inputs 10 and 5, my avg outcome is giving me 8. any help # Initialize the total count variable to 0
total_books = 0
Prompt the user for the first input
book_count = input("Enter the number of books read (or 0 to stop): ")
Continue the loop until the sentinel value "0" is entered
while book_count != "0": # Convert the input to an integer and add it to the total count total_books += int(book_count)
# Prompt the user for the next input
book_count = input("Enter the number of books read (or 0 to stop): ")Display the total number of books read
print("The total number of books read is:", total_books)
Creating the average using total_books
n = total_books total_numbers = n sum = 0 while n >= 0: sum += n n -= 1
average = sum / total_numbers print(("Average = %f") % average)
*outcome
Enter the number of books read (or 0 to stop): 10
Enter the number of books read (or 0 to stop): 5 Enter the number of books read (or 0 to stop): 0 The total number of books read is: 15 Average = 8.000000