Search code examples
pythonaverage

Syntax error calculating the average of student marks while reading from a text file


f = open('studMarks.txt', 'r')
marks = 0
# Sort out names, split the words then sort which order
    for line in f:
    words = line.split()
    fname = words[0]
    lname = words[1]
    print(f"{lname},{fname}")
f.close()

f = open('studMarks.txt', 'r')
sum = 0
count = 0
for line in f:
    count += 1
    sum += float(line.split()[2])
    n = []
average = sum/count

print(f"{average}")

When using the for loop it seems to display a value of 64.3, which I believe is for the total of the whole student list and average for all marks.

I need to produce the an output which displays the student names and average on the same line. I can do for the names but I cannot do it for the average as I keep getting errors. I don't know what to input in.


Solution

  • Below is the full solution. The with open line is a context manager and ensures that the file will get closed as soon as you exit the block. You should get used to using this style as it's the safe way to do I/O. The rest is just bog standard Python.

    marks=dict()
    with open('studMarks.txt', 'r') as f:
        for line in f:
            words = line.split()
            fname = words[0]
            lname = words[1]
            score = int(words[2])
            key = f'{fname} {lname}'
            count_key = f'{fname} {lname}_count'
            latest_score = score + (marks.get(key)[0] if marks.get(key) else 0)
            latest_count = 1 + (marks.get(key)[1] if marks.get(key) else 0)
            marks[key] = (latest_score, latest_count )
    for name, value in marks.items():
        print(f'{name} : {value[0]/value[1]}')