Question: give a program that matches this example. Calculating the Average of Numbers in a File # Step 1 : Prompt the user for the file

give a program that matches this example. Calculating the Average of Numbers in a File
# Step 1: Prompt the user for the file name
file_name = input("Enter the name of the file containing numbers: ")
try:
# Step 2: Open the file in read mode
with open(file_name, "r") as file:
# Step 3: Read the numbers from the file
numbers =[float(line.strip()) for line in file]
# Step 4: Calculate the average
if numbers:
average = sum(numbers)/ len(numbers)
# Step 5: Print the average
print(f"The average of the numbers in the file is: {average:.2f}")
else:
print("The file is empty. No numbers to calculate.")
except FileNotFoundError:
print("The specified file does not exist. Please try again.")
except ValueError:
print("The file contains invalid data. Please ensure the file only has numbers.")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!