Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

PYTHON Assuming that a file containing a series of integers is named number.txt

ID: 3574905 • Letter: P

Question

PYTHON

Assuming that a file containing a series of integers is named number.txt and exists on the computers disk. Write a program that calculates the average of all of the numbers.

This is still a fairly new subject to me so I'm hitting a wall here. I need my average of numbers to be created from numbers generated from a text file, read, accumulated, and then divided by how many number entries there are. Doesn't need to be fancy. Here is something that ive been tinkering with but its blows up and i feel like its not hitting the mark from a logic standpoint either.

def main():

    with open("numbers.txt") as myfile:
        average = [next(myfile) for x in range()]/len(myfile)
print(average)


main()

Explanation / Answer

Please find the required program along with its output. Please see the comments against each line to understand the step.

def main():
average = 0 #initialize the variables
nums = 0
with open("numbers.txt") as myfile: #open the file numbers.txt
array = [] #initialize an array to store numbers
for line in myfile: # for each line in the file
array.append([int(x) for x in line.split()]) #add the line into array as a list
for l in array: #for each list in the array
for i in l: #for each int in the list
average = average + i #add the sum and nums
nums = nums + 1
  
average = average/nums #find the average
print("Average = ",average) #print the average
  
main()

-----------------------------------------------------------------

OUTPUT:

sh-4.3$ ls
main.py numbers.txt
sh-4.3$ cat numbers.txt   
4 5 2 9 10 6 8 1 3 2 8
sh-4.3$   
sh-4.3$ python main.py
('Average = ', 5)