Hi guys, first off just wanted to say that this website has been immensely helpful to me for my programming class. I asked a question to help with a lab a couple of weeks ago and was able to figure out the issue with the forums help, so thank you. As last time, I am not looking for the lab to be done for me, only to be pushed in the right direction.

Lab: Write a Python program which will read integer data from a text file, convert these string values to integers, create a list containing these integers, and then compute and output the average of the values stored in the list.

I am confused on how to convert the list into integers in a list which can than be computed. We have to use a function to compute the average.

So far my code is:

def avgcalc(myList):
    average = total/numcount
    return average

myFile = open("labIn.txt", "r")
for myLine in myFile:
    print myLine,

Obviously I still have a lot of work to do, right now it simply prints the numbers that are in the .txt file. I just have no idea how to take these numbers from the file and put them in a list. Thanks in advance daniweb!

I wanted to specifiy that the txt file contains this following:

57
83
99
12
45
81
74
30
29
66
95
87
42

Edited 5 Years Ago by bigredaltoid: Added context

First, your function needs to operate on something specific, like a list or array of integers.
You will need to collect the total in a variable (I called mine intTotal).
You will need to loop for the total count of elements in the array until you reach the end.
If the elements in the array are already converted to integers, you will just need to add them to the total.

def avgcalc(myList):
   intTotal = 0
   intCount = 0;
   intLenMyList = len(myList)
   
   while(intCount <  intLenMyList):
   	intTotal += myList[intCount]
   	intCount += 1

   return intTotal/intLenMyList

A suggestion for reading the file is to convert the data to integers as it is being read. Your average function will then have less to do.

## main ##
arr_intValues = []
myFile = open("c:/science/python/labIn.txt", "r")
for myLine in myFile:
   arr_intValues.append(int(myLine))
print avgcalc(arr_intValues)

And to make it simpler use built in sum and len method of sequence types.

data = """
57
83
99
12
45
81
74
30
29
66
95
87
42
""".strip().splitlines()

print('Average is %f' % (float(sum(int(n) for n in data))/len(data)))

Edited 5 Years Ago by pyTony: n/a

This question has already been answered. Start a new discussion instead.