Python
PyUnit Tutorial: Python Unit Testing Framework (with Example)
What is Unit Testing? Unit Testing in Python is done to identify bugs early in the development stage of...
The formula to calculate average is done by calculating the sum of the numbers in the list divided by the count of numbers in the list.
The average of a list can be done in many ways listed below:
In this Python tutorial, you will learn:
In this example, we have initialized the variable sum_num to zero and used for loop. The for-loop will loop through the elements present in the list, and each number is added and saved inside the sum_num variable. The average is calculated by using the sum_num divided by the count of the numbers in the list using len() built-in function.
def cal_average(num): sum_num = 0 for t in num: sum_num = sum_num + t avg = sum_num / len(num) return avg print("The average is", cal_average([18,25,3,41,5]))
Output:
The average is 18.4
In this example the sum() and len() built-in functions are used. It is a straight forward way to calculate the average as you don't have to loop through the elements, and also, the code size is reduced. The average can be calculated with just one line of code as shown below.
# Example to find average of list number_list = [45, 34, 10, 36, 12, 6, 80] avg = sum(number_list)/len(number_list) print("The average is ", round(avg,2))
Output:
The average is 31.86
You can easily calculate the "average" using the mean function from the statistics module. Example shown below
# Example to find the average of the list from statistics import mean number_list = [45, 34, 10, 36, 12, 6, 80] avg = mean(number_list) print("The average is ", round(avg,2))
Output:
The average is 31.86
Numpy library is commonly used library to work on large multi-dimensional arrays. It also has a large collection of mathematical functions to be used on arrays to perform various tasks. One important one is the mean() function that will give us the average for the list given.
# Example to find avearge of list from numpy import mean number_list = [45, 34, 10, 36, 12, 6, 80] avg = mean(number_list) print("The average is ", round(avg,2))
Output:
C:\pythontest>python testavg.py The average is 31.86
What is Unit Testing? Unit Testing in Python is done to identify bugs early in the development stage of...
What is Python Range? Python range() is a built-in function available with Python from...
What is Python strip()? Python strip() function is a part of built-in functions available in the...
Python Tutorial Summary In this Python tutorial for beginners, you will learn Python programming basics and...
A list is a container that contains different Python objects, which could be integers, words,...
In this tutorial, you will learn- How to print simple string? How to print blank lines Print end...