11.2 - High score table

Problem

Write a program that will ask the user to enter scores for 5 players.

Those scores should be displayed on screen and written to a text file.

REMEMBER – ‘\n’ will take a new line in a text file.

Enter score for player 1: 100
Enter score for player 2: 90
Enter score for player 3: 80
Enter score for player 4: 70
Enter score for player 5: 60

HIGH SCORE TABLE
Player 1 - 100 
Player 2 - 90 
Player 3 - 80 
Player 4 - 70 
Player 5 - 60
Player 1 - 100
Player 2 - 90
Player 3 - 80
Player 4 - 70
Player 5 - 60

 

1 Get scores IN  
OUT scores
2 Display scores IN scores
OUT  
3 Write scores to file IN scores
OUT  

 

1.1 Create a scores array of 5 integers
1.2 Repeat 5 times
1.3     Ask for score and add to scores
1.4 End repeat
1.5 return scores

2.1 Display "HIGH SCORE TABLE"
2.2 Repeat 5 times
2.3     display player and score
2.4 End repeat

3.1 Open scores.txt
3.2 Repeat 5 times
3.3     Write each score to file
3.4 End repeat
3.5 Close file

 

# Main
scores = get_scores()
display_scores(scores)
write_scores(scores)
def get_scores():
    scores = [0] * 5
    for i in range(5):
        scores[i] = int(input("Enter score for player " + str(i + 1) + ": "))
    return scores

def display_scores(scores):
    print("HIGH SCORE TABLE")
    for i in range(5):
        print("Player " + str(i + 1) + " - " + str(scores[i]))

def write_scores(scores):
    file = open("scores.txt", "w")
    for i in range(5):
        file.write("Player " + str(i + 1) + " - " + str(scores[i]) + "\n")
    file.close()

# Main
scores = get_scores()
display_scores(scores)
write_scores(scores)
# get_scores
# Asks the user to enter 5 scores and stores them in an array.
# The loop runs 5 times (for players 1–5).
# str(i + 1) is used so player numbers start from 1 instead of 0.
def get_scores():
    scores = [0] * 5
    for i in range(5):
        scores[i] = int(input("Enter score for player " + str(i + 1) + ": "))
    return scores

# display_scores
# Displays all scores on screen in a formatted list.
# The loop prints each player’s number and their score.
def display_scores(scores):
    print("HIGH SCORE TABLE")
    for i in range(5):
        print("Player " + str(i + 1) + " - " + str(scores[i]))

# write_scores
# Writes all scores to a text file, one per line.
# The "\n" adds a newline character so each player's score appears on a new line in the file.
def write_scores(scores):
    file = open("scores.txt", "w")
    for i in range(5):
        file.write("Player " + str(i + 1) + " - " + str(scores[i]) + "\n")
    file.close()

# Main
scores = get_scores()        # Ask the user to enter all scores
display_scores(scores)       # Show the scores on screen
write_scores(scores)         # Save the scores to a file

Extension

Update the program to ask for a name for each player. The names ans associated scores should be displayed and written to file.

Target

Write array data to file