In: Computer Science
Part 1: Write a program that finds the sum and average of a series of numbers entered by the user. The program will first ask the user how many numbers there are. It then prompts the user for each of the numbers in turn and prints out the sum, average, the list of number from the user. Note: the average should always be a float, even if the user inputs are all ints.
Part 2: Same as part 1 except now the numbers are to
be read in from a file.
File contains a single line of numbers delimited by comma. Example:
8, 39, 43, 1, 2, 3
Part 3: Part 2 but modular ( i.e. using
functions).
Assume the file name is passed to the function as a parameter. The
function then opens the file, reads in the numbers, then computes
and returns the sum and average of the numbers.
Part 1:
n=int(input('How many numbers there are??:'))
s=0
for i in range(n):
val=int(input('Enter number:'))
s=s+val
average=float(s/n)
print('Sum is:',s)
print('Average is:',average)
OUTPUT
Part2:
s=0
c=0
with open('file.txt','r') as f:
for line in f:
num=line.split(',')
for i in num:
s=s+int(i)
c=c+1
average=float(s/c)
print('Sum is:',s)
print('Average is:',average)
file.txt
OUTPUT
part3:
def fun(fname):
s=0
c=0 #used to count numbers present in file.
f=open(fname)
for line in f:
num=line.split(',') # it splits the line by , ( since numbers are separated by comma[,])
for i in num: #num contains list of numbers
s=s+int(i)
c=c+1
average=float(s/c)
return s,average
s,ave=fun('file.txt')
print('Sum is:',s)
print('Average is:',ave)
OUTPUT