In Python, Compute Average Of All Numbers In File
def read_all(path):
nums = None
try:
with open(path, 'r') as file:
for line in file:
if not nums:
nums = []
try:
nums.append(int(line.strip()))
except ValueError:
pass
except IOError as e:
print(e)
return nums
def average(nums):
if not nums:
return None
total = 0
count = 0
for num in nums:
total += num
count += 1
return total/count
if '__main__' == __name__:
nums = read_all('number.dat')
print(nums)
print('average', average(nums))
Download
Comments
Post a Comment