Python Lab Program 3
Python Lab Program 3
Part A
Read N numbers from the console and create a list. Develop a program and
standard deviation with suitable print mean, variance messages.
import math
def mean(data):
n = len(data)
mean_val = sum(data) / n
return mean_val
def variance(data):
n = len(data)
mean_val = mean(data)
deviations = [(x - mean_val) ** 2 for x in data]
variance_val = sum(deviations) / n
return variance_val
def stdev(data):
var = variance(data)
std_dev = math.sqrt(var)
return std_dev
listA = []
n = int(input("Enter the number of elements: "))
for i in range(n):
element = int(input("Enter element {}: ".format(i+1)))
listA.append(element)
print("List:", listA)
print("Mean of the sample is %s" % (mean(listA)))
print("Variance of the sample is %s" % (variance(listA)))
print("Standard Deviation of the sample is %s" % (stdev(listA)))
Output:
Enter the number of elements: 4
Enter element 1: 2
Enter element 2: 4
Enter element 3: 6
Enter element 4: 8
List: [2, 4, 6, 8]
Mean of the sample is 5.0
Variance of the sample is 5.0
Standard Deviation of the sample is 2.23606797749979
From lab manual
import math
def mean(data):
n = len(data)
mean_val = sum(data) / n
return mean_val
def variance(data):
n = len(data)
mean_val = mean(data)
deviations = [(x - mean_val) ** 2 for x in data]
variance_val = sum(deviations) / n
return variance_val
def stdev(data):
var = variance(data)
std_dev = math.sqrt(var)
return std_dev
listA = []
n = int(input("Enter the number of elements: "))
for i in range(n):
element = int(input())
listA.append(element)
print("List:", listA)
print("Mean of the sample is %s" % (mean(listA)))
print("Variance of the sample is %s" % (variance(listA)))
print("Standard Deviation of the sample is %s" % (stdev(listA)))
Algorithm:
1. Start
2. Initialize an empty list listA.
• For each element x in data, compute the squared deviation from the mean: (x -
mean)^2.
12.End
Output:
Enter the number of elements: 4
2
4
6
8
List: [2, 4, 6, 8]
Mean of the sample is 5.0
Variance of the sample is 5.0
Standard Deviation of the sample is 2.23606797749979