Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Help | Read data from text file from the bottom

Can someone have a look at my program? There's an error which I cannot identify and it's really confusing me. Also, please explain to me the problem so that I can understand how to use the function and program in another situation.

input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'

while open(datafile, 'r') as f:
    data = {}
    for line in f:
        name, value = line.split('=')
        name = name.strip
        value = str(value)
        data.setdefault(name, []).append(value)
else:
    break
avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

print("\n", input_name,"'s average score is", avg(input_name))
like image 955
GameFederer Avatar asked Feb 11 '26 02:02

GameFederer


1 Answers

Single steps

Read all data into a dict:

data = {}
for line in f:
    name, value = line.split('=')
    name = name.strip()
    value = int(value)
    data.setdefault(name, []).append(value)

The content of data:

{'Chris': [9, 9],
 'John': [6, 4, 5],
 'Sarah': [4, 7],
 'Tanzil': [4, 4, 10, 5, 3],
 'Tom': [2]}

Now you can calculate the average:

last_scores = data['Tanzil'][-3:]
avg = sum(last_scores) / len(last_scores)


>>> avg
6.0

or averages for all:

avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

now avg holds:

{'Chris': 9.0, 'John': 5.0, 'Sarah': 5.5, 'Tanzil': 6.0, 'Tom': 2.0}

Show all results:

for name, value in avg.items():
    print(name, value)

prints:

Tanzil 6.0
Chris 9.0
Sarah 5.5
John 5.0
Tom 2.0

or nicely ordered highest to lowest average score:

from operator import  itemgetter

for name, value in sorted(avg.items(), key=itemgetter(1), reverse=True):
        print(name, value)

prints:

Chris 9.0
Tanzil 6.0
Sarah 5.5
John 5.0
Tom 2.0

Full program

input_name = input("\nPlease enter students name » ").strip()
datafile = '1.txt'

with open(datafile, 'r') as f:
    data = {}
    for line in f:
        name, value = line.split('=')
        name = name.strip()
        value = int(value)
        data.setdefault(name, []).append(value)

avg = {}
for name, scores in data.items():
    last_scores = scores[-3:]
    avg[name] = sum(last_scores) / len(last_scores)

print("\n", input_name,"'s average score is", avg[input_name])
like image 197
Mike Müller Avatar answered Feb 13 '26 15:02

Mike Müller