What is the usage of the average function in Python?

In Python, the average can be calculated using the average() function. However, the standard library in Python does not directly provide the average() function, but it can be implemented using other methods.

A common method is to calculate the average using the sum() and len() functions. You can first add up a set of numbers and then divide by the number of digits to obtain the average, for example:

numbers = [1, 2, 3, 4, 5]
average = sum(numbers) / len(numbers)
print(average)

Output:

3.0

Another approach is to calculate the average using the mean() function in the statistics module. Import the module first, then use the mean() function directly to compute the average. For example:

import statistics

numbers = [1, 2, 3, 4, 5]
average = statistics.mean(numbers)
print(average)

Output:

3

Please note that the statistics module was introduced in Python 3.4 and above; if you are using an earlier version of Python, you will need to use alternative methods to calculate the average.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds