In Python, Read Integers From File To Compute Sum And Average

 


try:
    with open('numbers.dat','r') as file:
        total = 0
        count = 0
        for line in file:
            line = line.strip()
            if not line:
                continue
            try:
                num = int(line)
                total += num
                count += 1
            except ValueError:
                print('Skipped line:',line)
        print('sum: %.2f' % total)
        avg = total/count*1.0
        print('avg: %.2f' % avg)
except IOError:
    print('Something went wrong!')
Download

Comments

Popular posts from this blog