In: Computer Science
9) This is in Python
Code a program that allows the user to manage its expenses accepting the following commands:
- Add <player_name> -> This command adds a new player to the system. Assume there can’t be repeated names. If a name already exists then an error is shown to the user.
- Score <player_name> <score> -> This command adds the score to the player with the name player-name. Each score needs to be added individually
- Report -> This commands prints the name of each player and the top three scores they have. If they have less than three scores then it prints all of the scores for that player. After printing each name and the top three scores for each player it prints the total score for all players
-Exit -> Stops the program
Python Program:
""" Python program that executes based on commands """
# Initializing players dictionary
players = {};
# Loop user want to exit
while True:
# Reading commands
command = input("Enter your Command: ")
# Splitting on space
tokens = command.strip().split()
# Fetching first word of command
cmd = tokens[0]
# Checking command
if cmd.lower() == 'add':
# Reading name
name = tokens[1]
# Checking for existence
if name in players.keys():
print("\nPlayer
", name, "already exists...\n")
else:
# Adding
player
players[name] =
[]
# Command is Score
elif cmd.lower() == 'score':
# Reading name
name = tokens[1]
# Checking for existence
if name not in
players.keys():
print("\nPlayer
", name, "doesn't exist...\n")
else:
# Adding
score
players[name].append(float(tokens[2]))
# Command is Report
elif cmd.lower() == 'report':
# Printing player name and
score
for player in players.keys():
# Sorting
scores
players[player].sort(reverse=True)
# Printing
data
print("\nPlayer:
", player, end = "\t")
# Printing
scores
if
len(players[player]) >= 3:
print("Scores: ", players[player][0],
players[player][1], players[player][2])
else:
print("Scores: ",end="")
for score in players[player]:
print(score, end=" ")
# Total score of all players
total = 0
for player in players.keys():
for score in
players[player]:
total = total + score
# Printing total score
print("\n\nTotal Score: ", total,
"\n\n")
# Command is Exit
elif cmd.lower() == 'exit':
print("Bye!")
break
# any other command
else:
print("Invalid Command")
_______________________________________________________________________________________________________________________
Code Screenshot:
_______________________________________________________________________________________________________________________
Sample Run: