Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

- - Coding Problem 4.4.2 (External resource) (30 points possible) Averaging.py S

ID: 3704174 • Letter: #

Question

- - Coding Problem 4.4.2 (External resource) (30 points possible) Averaging.py Submit Ru Grades Reset 1 #write a function called average average file should Console output will be displayed here 2 #have one e Paremeter: filenam.ale. 4 #The file should have an integer on each line. average file 5 #should return the average of these intege However, if 6 #any of the lines of thefile are not integers 7 #average file should return the string "Error reading file! 8# 9 #Remember, by default, every time you read a line from 10 #file, it's interpreted as a string 12 13 #Add your function here! 14 15 17 #aelow are some lines of code that will test your function 18 #You can change the value of the variable(s) to test your 19 #function with different inputs 20 21 #if-yourfunction works correctly, this will originally 22 #print: 5.8, then Error reading file! 23 # 24 #You can select valid file.txt and invalid file.txt from 25 #the dropdown in the top left to preview their contents 26 print (everagefile velid file.txt)) 27 print (everage file( invalid file.txt)) 28 29

Explanation / Answer

def average_file(filename): avg = 0 count = 0 try: with open(filename, 'r') as f: for line in f: avg += float(line.strip()) count += 1 except: return "Error reading file!" return avg / count print(average_file('input.txt'))