The High Scores 2.0 Program

This is an example program from:

Dawson, M. (2010). Python programming for the absolute beginner, third edition (3rd ed.). Delmar Cengage Learning.

We can extend the functionality of our previous High Scores Program by changing the data structure that we use.

Now instead of storing just the score in a list. We now store the person's name and the score. Do do this we will use tuples inside a list. This is an example of a nested sequence.

scores = [(person_1, score_1), (person_2, score_2), ...]

For example,

scores = [("Sam", 3), (Bradley, 9999), ...]

Clearly I lost!

The following program shows how to use this to extend the listing/adding scores functionality. Run the code to see how it works.

You might want to consider rewriting the whole program for practice.

# High Scores 2.0
# Demonstrates nested sequences
scores = []
choice = None
while choice != "0":
    print(
        """
  High Scores 2.0
  0 - Quit
  1 - List Scores
  2 - Add a Score
  """
    )
    choice = input("Choice: \n")

    # exit
    if choice == "0":
        print("Good-bye.")
    # display high-score table
    elif choice == "1":
        print("High Scores\n")
        print("NAME\tSCORE")
        for entry in scores:
            score, name = entry
            print(name, "\t", score)
    # add a score
    elif choice == "2":
        name = input("What is the player's name?: ")
        score = int(input("What score did the player get?: "))
        entry = (score, name)
        scores.append(entry)  # append entry
        scores.sort(reverse=True)  # sort the list. Highest first
        scores = scores[:5]  # keep only top 5 scores
    # some unknown choice
    else:
        print("Sorry, but", choice, "isn't a valid choice.")

input("\n\nPress the enter key to exit.")