Home > Enterprise >  Program that reads a file and displays the sum and average of the numbers in the file
Program that reads a file and displays the sum and average of the numbers in the file

Time:04-01

I'm trying to solve the following problem: Write aprogram that reads the random numbers from the file random_numbers.txt, displays the numbers, then displays the following data: a. The total (sum) of the numbers b. The number of random numbers read from the file c. The average value of the numbers read from the file

Here's what i Have so far

sum = 0
runs = 0
avg = 0

myfile = open("random_number.txt", "r")

file_contents = myfile.read()

print(file_contents)

for i in myfile.readlines():

    number = i
    sum  = number

print("the sum is", sum)

I don't know why the sum displays 0?

CodePudding user response:

use this maybe slove your problem

sum = 0
runs = 0
avg = 0

myfile = open("random_number.txt", "r")
file_contents  = myfile.readlines()
for i in file_contents:
    #print(i)
    number = i
    sum  = int(number)

print("the sum is", sum)

CodePudding user response:

After executing file_contents = myfile.read(), myfile is empty. You can You can check by printing in loop statement for i in file_contents:
I fixed your code

sum = 0
runs = 0
avg = 0

with open("random_number.txt", "r") as myfile:
    for i in myfile:
        number = eval(i)
        sum  = number
print("the sum is", sum)

  • Related