The Python statistics module has a number of useful functions. Lets discuss some code snippets and understand how to use statistical functions in Python statistics module.
Calculating mean value of given data
The mean value of a given data set is the average value of the data. Mean can be calculated by adding all the numbers and dividing the sum by the number of values.
In statistics module of Python, the mean() function calculates the mean value of a given list of numbers and returns the mean as a float value.
# program to find the mean value of given list of numbers
import statistics
numbers = []
while True:
n = float(input("Enter a number "))
if n==0:
break
numbers.append(n)
mean = statistics.mean(numbers)
print("The given numbers are ", numbers)
print("The mean is ", mean)
Recommended Reading
For detailed information on calculating the mean value and using other functions like fmean() and geometric_mean(), read this article on using mean function in statistics module.
Calculating median value of given data
The median value of a given data set is the middle value of the data. Median can be calculated by sorting the numbers in ascending order and finding the value in the middle of the list. If there are two values in the middle, then the average of the two values is returned.
In statistics module of Python, the median() function calculates the median value of a given list of numbers and returns the median as a float value.
# program to find the median value of given list of numbers
import statistics
numbers = []
while True:
n = float(input("Enter a number "))
if n==0:
break
numbers.append(n)
median = statistics.median(numbers)
print("The given numbers are ", numbers)
print("The median is ", median)
Recommended Reading
For detailed information on calculating the median value and using other functions like median_low() and median_high(), read this article on using median function in statistics module.
Calculating mode of given data
The mode value of a given data set is the value which occurs the most. Mode can be calculated by counting the frequency of each value. The value with the highest frequency is the mode. If there are two values with the same highest frequency, then the first encountered value is returned as the mode.
In statistics module of Python, the mode() function calculates the mode value of a given list of numbers and returns the mode as a float value.
# program to find the mode value of given list of numbers
import statistics
numbers = []
while True:
n = float(input("Enter a number "))
if n==0:
break
numbers.append(n)
mode = statistics.mode(numbers)
print("The given numbers are ", numbers)
print("The mode is ", mode)
Recommended Reading
For detailed information on calculating the mode value and using other functions like mode() and multimode(), read this article on using mode function in statistics module.