PYTHON Average of Numbers Assume that a file containing a series of integers is
ID: 3711739 • Letter: P
Question
PYTHON
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. (You may chose to create a sample text file to test your program.) Then modify the program so it handles the following exceptions: It should handle any IOError exceptions that are raised when the file is opened and data is read from it. It should handle any ValueError exceptions that are raised when the items that are read from the file are converted to a number. Next, copy the code from Visual Studio and paste the code directly into your original post to this discussion topic. In your post, share with your classmates your experience with creating your program and why you chose your algorithm.
Explanation / Answer
PROGRAM
import sys
# Initialize 0 to two variables count and sum1
count=0
sum1=0
try: # open try except block for open file and integer elements in the file or not
f = open('f: umbers.txt') # open file in read mode
s = f.readline() # reading the first element from the file
s= s.rstrip(' ') # rstrip() is used to every new line of the file content
while s!="": # setting up loop to continue reading until an empty line is reached
s=int(s) # convert from string to integer number
print(s) # display numbers in the file
count=count+1 # increment counter by 1 used for counting number of integer elements
sum1=sum1+s # calulate sum of elements
s=f.readline() # reading next element from the file
s=s.rstrip(' ') # every new line of the file content
print('Sum of Intger Numbers: ',sum1) # display sum of elements
avg=sum1/count # calculate average of elements
print('Average Integer Numbers: ',avg) # display average elements in the file
except IOError as e: # catch IOError if the file not available
print(e) # then display exception of the file
except ValueError: # catch ValueError if there is no Integer numbers
print("No valid integer numbers.")
except:
print("Unexpected error:", sys.exc_info()[0])
raise
OUTPUT
5
2
6
1
8
3
9
Sum of Intger Numbers: 34
Average Integer Numbers: 4.857142857142857
OUTPUT-2
[Errno 2] No such file or directory: 'numbers.txt' (if the file not exists in the directory)
OUTPUT-3
No valid integer numbers. ( if the file contains real number such as 4.3, 6.4, 5.3 etc.,)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.