You need to parse the numbers, int(number)
will do that (if your input file contains one number per line) - then you add the number to a list (define it before the for
as allNumbers = []
so you do not reinitialize it all the time to empty list inside the for. append your parsed number to it with allNumbers.append(mynumber)
.
Outside the for loop you return the numbers in the list:
The avg Function will compute the average (also see: Finding the average of a list )
def avg(myl):
return (sum(myl)+0.0) / len(myl) # + 0.0 needed in 2.x to make it a float
def readNumbersFromFile( filename ):
'''Function that takes a filepath and parses it. The file is required to
consist out of integer numbers only - text or floating point numbers
are not handled and lead to exceptions. The file format allows for
multiple integer numbers seperated by spaces per line and for multiple
lines and will parse all numbers into one flat list and return it.'''
numbersFile = open (filename, 'r') # open file for read
allNumbers = [] # result list
for line in numbersFile: # reads one line
for number in line.split(" "): # splits one line into single numbers
allNumbers.append(int(number)) # adds each number as integer to list
return allNumbers # returns the list from this function
nums = readNumbersFromFile(r'numbers.dat')
print("The average is ", avg(nums))
My avg-computing uses the build-in sum
- you could also compute the avg yourself by adding all elements in the list and dividing by the amount of items in the list