Table of Contents

Python code to Calculate sum and average of a list of Numbers.

 

Python code implementation without user-defined functions & classes

Code: 
#Python code to Calculate sum and average of a list of Numbers.
from math import fsum
from statistics import mean

a = input("Enter list separated by space: ").split()
b = []
for i in a:
    b.append(float(i))

sum_of_list = fsum(b)
avg_of_list = mean(b)

print(sum_of_list)
print(avg_of_list)

 

Executing Python Script: 
python program.py
Enter list separated by space: 34 45 67 12 13 9 72 35

 

Output: 
287.0
35.875

 

 

Python code implementation using function

Code: 
#Python code to Calculate sum and average of a list of Numbers using function.
from math import fsum
from statistics import mean

def sum_avg_of_list(list_arg):
    b = []
    for i in list_arg:
        b.append(float(i))
    print(fsum(b))
    print(mean(b))

a = input("Enter list separated by space: ").split()

sum_avg_of_list(a)

 

Executing Python Script: 
python program.py
Enter list separated by space: 34 45 67 12 13 9 72 35

 

Output: 
287.0
35.875

 

 

 

Python code implementation using Classes

Code: 
# Python code to Calculate sum and average of a list of Numbers.
from math import fsum
from statistics import mean


class Sum_avg_of_list(object):
    __b = []
    def __init__(self, a):
        self.a = a

        for i in self.a:
            Sum_avg_of_list.__b.append(float(i))

    def sum_of_list(self):
        return fsum(Sum_avg_of_list.__b)

    def avg_of_list(self):
        return mean(Sum_avg_of_list.__b)


entered_list = input("Enter list separated by space: ").split()

# Create an Object
Object_1 = Sum_avg_of_list(entered_list)

# #Call the function using Object

print(Object_1.sum_of_list())
print(Object_1.avg_of_list())

 

Executing Python Script: 
python program.py
Enter list separated by space: 34 45 67 12 13 9 72 35

 

Output: 
287.0
35.875

 

 

 

 

Enjoy Python Code By Pythonbaba 🙂