Python Forum

Full Version: Calcolate the average of numbers from a .txt file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I start to learn programming few weeks ago and I'm trying to do an exercise that ask me to calculate the average of a list of number from a text file. This is my code:
file=input('Enter a file name: ')
open=open(file)
count=0
for line in open:
    line=line.rstrip()
    if line.startswith('X-DSPAM-Confidence:'):
        count=count+1
        search=line.find(':')
        numbers=line[search+1:]
        float(numbers)
        Media=sum(numbers)/count
        print('Media spam confidence: ', Media)
It gives me back this error:
Error:
Traceback (most recent call last): File "C:\Users\frank\OneDrive\Documenti\Atom\Esercizi\Esercizio_file.py", line 11, in <module> Media=sum(numbers)/count TypeError: unsupported operand type(s) for +: 'int' and 'str'
I understand the error but I don't know how to fix it
On line 10 float(numbers) dos nothing as it not saved in a variable.
Then will make this error.
>>> n = '0.4855'
>>> count = 5
>>> sum(n) / 5
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

# But dos not help is save variable as will get new error
>>> n = float(n)
>>> sum(n) / 5
Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
TypeError: 'float' object is not iterable
 
So untested if you parse numbers correct could make another variable total at top.
Then calculate average when loop is finish.
file = input('Enter a file name: ')
f_open = open(file) # open is used bye Python
count = 0
total = 0
for line in f_open:
    line = line.rstrip()
    if line.startswith('X-DSPAM-Confidence:'):
        search = line.find(':')
        numbers = line[search+1:]
        count = count + 1
        total = total + float(numbers)

average = total / count
print(f"Average confidence: {average}")
Thank you so much