+ 1

PLEASE HELP: why doesn't this program work? its probably pretty wrong, not sure whats going on

ASSIGNMENT: Download the file numbers.txt attached to this assignment. The file contains mostly numbers, but every so often, there is a string. Write a program NumberAverage.py to average all the numbers, ignoring the values that are not numbers. Hint: use exception handling to determine whether the data on the current line is a number or not. Example execution: There are 80 numbers in the file and their average is 51.92. fo = open("numbers.txt", 'r') line = fo.read().rstrip('\n') numLines = 0 sumNumbers = 0 for i in line: numLines += 1 try: sumNumbers += int(i) except ValueError or TypeError: sumNumbers += 0 line = fo.read().rstrip('\n') average = sumNumbers / numLines print("There were " + numLines + " numbers in the file and they had an average of " + average + ".") when I run this, I get "can only concatenate str (not "int") to str"

10th May 2021, 4:14 PM
Henry Fournier
Henry Fournier - avatar
3 Answers
+ 1
you need to cast numLines and average to a string in the print function
10th May 2021, 4:25 PM
Xixi
0
When i do this, I get "There were 1706 numbers in the file and they had an average of 3.6658851113716295." I should be getting 80 numbers with an average of 50 something. i think its because of the stripping? do you know how to fix it?
10th May 2021, 4:37 PM
Henry Fournier
Henry Fournier - avatar
0
yh when you loop through, it is looping through each whitespace and digit, instead of each number try fo.read.split() instead of the rstrip line
10th May 2021, 4:55 PM
Xixi