Question: Goal: Recap knowledge learned about reading files and converting values. Assignments: A file named players.txt tracks the performance of each player this season. On one

Goal: Recap knowledge learned about reading files and converting values.
Assignments: A file named players.txt tracks the performance of each player this season. On one line the name of the player is stored, and on the following, the number of goals scored.
Write a program that reads the file, and displays the name of the player that scored the most goals. During the bookkeeping, however, errors often occur, which means some of the numbers may contain typos like 2O, where the second character is a capital O and not a zero. Accounting for this, if you encounter an error, display the name of the player for whom the score cannot be converted with an asterisk at the end.
Sample players.txt
F. Reddley
1
L. Brukworn
0
M. M. Saad
1
T. Morey
O
A. Fox
2
L. Bromley J
r1
J. S. Abrahms
3
F. Inchat
0
Sample Run
T. Morey*
L. Bromley J*
J. S. Abrahms is the MVP!
My python code: but it still shows it's wrong, I don't understand. It supposed to have 3 lines as above, but it is missing T. Morey*, so what am I missing, what did I do wrong?
def find_mvp(filename):
try:
with open(filename,"r") as file:
lines = file.readlines()
players_scores ={}
error_players =[]
i =0
while i < len(lines):
player = lines[i].strip()
i +=1
if i < len(lines):
score_str = lines[i].strip()
try:
# Replace 'O' with '0' for valid conversion
score = int(score_str.replace('O','0'))
players_scores[player]= score
except ValueError:
error_players.append(f"{player}*")
i +=1
# Ensure all error players are printed in one line
if error_players:
print("".join(error_players))
if players_scores:
mvp = max(players_scores, key=players_scores.get)
print(f"{mvp} is the MVP!")
except FileNotFoundError:
print("Could not find the file.")
except Exception as e:
print(f"An error occurred: {e}")
# Call the function with the name of your file
find_mvp("players.txt")

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!