SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Tony Gaddis
Chapter:
Files And Exceptions
Exercise:
Programming Exercises
Question:6 | ISBN:9780132576376 | Edition: 2

Question

Average of Numbers
Assume that a file containing a series of integers is named numbers.txt and exists on the computer’s disk. Write a program that calculates the average of all the numbers stored in the file.

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

Average of Numbers Python code:

#a file containing a series of integers
#is named numbers.txt 
inputFile = "numbers.txt"

#Calculates the average of all the numbers 
#stored in the file.
try:
    with open(inputFile, 'r') as file:
        numbers = file.read().split()
        total = sum(map(int, numbers))
        count = len(numbers)
        
        if count > 0:
            average = total / count
            print(f"The average of the numbers in '{inputFile}' is: {average}")
        else:
            print(f"The file '{inputFile}' is empty.")

except FileNotFoundError:
    print(f"File '{inputFile}' not found.")
except IOError:
    print(f"An error occurred while reading the file '{inputFile}'.")
except ValueError:
    print(f"The file '{inputFile}' contains non-integer values.")

Data in "numbers.txt" file:

5 
10
20
40
5
95
20
30

Executed Output:

The average of the numbers in 'numbers.txt' is: 28.125

 

0 0

Discussions

Post the discussion to improve the above solution.