Python programs · NumPy
Python program to find the mean, median and standard deviation with NumPy
NumPy summarises a list of numbers in one line each. This is the usual way to analyse marks, temperatures or prices.
Approach
- Put the numbers in a NumPy array.
- Call
.mean(),np.median()and.std(). - Round the standard deviation for a tidy result.
The program
import numpy as np marks = np.array([72, 85, 90, 64, 78]) print("Mean:", marks.mean()) print("Median:", np.median(marks)) print("Std:", round(marks.std(), 2))
Sample run
Output
Mean: 77.8 Median: 78.0 Std: 9.22
How the code works
The mean is the sum divided by the count, (72 + 85 + 90 + 64 + 78) ÷ 5 = 77.8. The median is the middle value after sorting, which is 78. The standard deviation measures how far the marks spread from the mean; NumPy's .std() divides by the number of values (the population version). round(..., 2) keeps two decimals.
Try changing it
- Find the highest and lowest marks with
marks.max()andmarks.min(). - Count how many marks are above the mean with
(marks > marks.mean()).sum().
Common mistakes
- Forgetting
import numpy as np, which gives a NameError. - Calling
np.meanon a plain text string instead of numbers.