Python Forum
Homework question: Python file handling and average calculation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Homework question: Python file handling and average calculation
#1
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:

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
Reply
#2
check your indentation under the for loop.
All lines included in the for loop must be indented the same amount, traditionally 4 spaces.
Same with the dictionary.

hint:
mydict = {
    item1,
    item2
}
the variables within in the loop do not match those in the for loop itself.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  research question: pypi authors handling user questions JohnAD 0 2,190 Oct-16-2019, 02:55 AM
Last Post: JohnAD

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020