Sep-21-2026, 03:04 AM
I’m working on a Python homework assignment about reading data from a text file and calculating the average score of the students.
The assignment asks me to:
Read student names and scores from a text file.
Calculate the average score for each student.
Display the student with the highest average score.
I tried to write the program myself, but I’m having trouble when I calculate the average. My program works for some inputs, but sometimes I get an error or an incorrect result.
Here is a simplified version of my code:
I think the problem may be related to the way I use max(), but I’m not sure how to fix it.
What I have tried:
I checked the values stored in the averages dictionary.
I used sum() and len() to calculate the averages.
I searched for examples of using max() with dictionaries, but I’m still confused about how it works.
Could someone explain what is wrong with my use of max() and give me a hint about how I should approach it? I’d like to understand the solution rather than just copy the code.
System information:
Python: 3.12
OS: Windows 11
IDE: Visual Studio Code
The assignment asks me to:
Read student names and scores from a text file.
Calculate the average score for each student.
Display the student with the highest average score.
I tried to write the program myself, but I’m having trouble when I calculate the average. My program works for some inputs, but sometimes I get an error or an incorrect result.
Here is a simplified version of my code:
students = {
"Anna": [8, 7, 9],
"Ben": [6, 8, 7],
"Chris": [9, 10, 8]
}
averages = {}
for name, scores in students.items():
total = sum(scores)
average = total / len(scores)
averages[name] = average
highest = max(averages)
print("Average scores:", averages)
print("Student with the highest average:", highest)The output I expected was that Chris would have the highest average. However, the program prints the wrong student.I think the problem may be related to the way I use max(), but I’m not sure how to fix it.
What I have tried:
I checked the values stored in the averages dictionary.
I used sum() and len() to calculate the averages.
I searched for examples of using max() with dictionaries, but I’m still confused about how it works.
Could someone explain what is wrong with my use of max() and give me a hint about how I should approach it? I’d like to understand the solution rather than just copy the code.
System information:
Python: 3.12
OS: Windows 11
IDE: Visual Studio Code
