In: Computer Science
Python Language Only!
Python Language Only!
Python Language Only!
Python 3 is used.
When doing this try to use a level one skill python, like as if you just learned this don't use anything advanced if you can please. If not then do it as you can.
Assume you have a file on your disk named floatnumbers.txt containing float numbers. Write a Python code that reads all the numbers in the file and display their average. Your code must handle any IOError (for example, file does not exist) and ValueError (for example, alphanumeric data found in the file such as letters) exceptions.
If you have any doubts, please ask in the comments, I will try to solve it as soon as possible. If you find my answer helpful, do UPVOTE.Thanks
The required Python code is given below:
#sum of numbers
sum = 0
#count of numbers
numbers = 0
#opening file
try:
with open("floatnumbers.txt","r") as file:
#reading each number
for line in file.readlines():
try:
#updating the sum
sum=sum+float(line)
#updating the number count
numbers=numbers+1
#handling the ValueError
except ValueError:
print("Oops cannot convert string to float")
#handling the IO error
except IOError:
print("File does not exist")
if numbers > 0:
#printing the average if count is greater than zero
print("Average: " + str(sum/numbers))
Code Snippet:
Output:
floatnumbers.txt
#sum of numbers sum = 0 #count of numbers numbers = 0 #opening file try: with open("floatnumbers.txt","r") as file: #reading each number for line in file.readlines(): try: #updating the sum sum=sum+float(line) #updating the number count numbers-number3+1 #handling the ValueError except ValueError: print ("Oops cannot convert string to float") #handling the Io error except IOError: print ("File does not exist") if numbers > 0: #printing the average if count is greater than zero print ("Average: " + str(sum/numbers))
Oops cannot convert string to float Average: 6.55