Python 2.7 mean, sum of the list -


i new python , having assignment trying sum , averge of list read txt file. code have come is:

def filetolist (filename):     result = []     try:         f = open (filename,'r')         l in f.readlines ():             result.append (l.strip())         return result     except ioerror:          print ('file name not correct!')         return []  infile = raw_input ('please enter file.txt : ') lines = filetolist (infile) list in lines:     print (l) 

it works , returns values struggling how calculate them?

i assume input file contains floats, 1 number per line. following program ignores blank lines , takes care of edge case when there not numbers @ all.

btw don't exception handling. hides actual reason. imho it's better not handle exception. give user better feedback went wrong.

def calc_stats(filename):     sum = 0.0     cnt = 0     line in open(filename,"rt"):         line = line.strip()         if not line:             continue # skip blank lines         sum += float(line)         cnt += 1     return (sum, cnt)  infile = raw_input ('please enter file.txt : ') sum, cnt = calc_stats(infile) if cnt == 0:     print("sum=%f, count=%d" % (sum, cnt)) else:             print("sum=%f, count=%d, average=%f" % (sum, cnt, sum/cnt)) 

Comments

Popular posts from this blog

javascript - Slick Slider width recalculation -

jsf - PrimeFaces Datatable - What is f:facet actually doing? -

angular2 services - Angular 2 RC 4 Http post not firing -