MP: The High Scores Program

This is an example program from:

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

The following is a mini-program that demonstrates the use of lists to add, store, remove and access information.

It is a simple high scores program, not exactly useful without a game attached to it, but it illustrates the concepts.

Note the use of choice = None. This is useful to get the program started when we don't yet have a user defined choice.

Run the code to see what it does.

# High Scores 1.0
# Demonstrates list methods
scores = []
choice = None

while choice != "0":
    print(
        """
  High Scores
  0 - Exit
  1 - Show Scores
  2 - Add a Score
  3 - Delete a Score
  4 - Sort Scores
  """
    )
    choice = input("Choice: ")
    print()

    # exit
    if choice == "0":
        print("Good-bye.")
    # list high-score table
    elif choice == "1":
        print("High Scores")
        for score in scores:
            print(score)
    # add a score
    elif choice == "2":
        score = int(input("What score did you get?: "))
        scores.append(score)
    # remove a score
    elif choice == "3":
        score = int(input("Remove which score?: "))
        if score in scores:
            scores.remove(score)
        else:
            print(score, "isn't in the high scores list.")
    # sort scores
    elif choice == "4":
        scores.sort(reverse=True)
    # some unknown choice
    else:
        print("Sorry, but", choice, "isn't a valid choice.")

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

Note that you could refactor this code by moving each of the choices into a function. Here we have put the removal of a score into a function.

# This demonstrates that when you pass a list, you are accessing the original list, not a copy! 
def remove_score(score, scores):
    if score in scores:
        scores.remove(score)
    else:
        print(score, "isn't in the high scores list.")
.    
.    # rest of code as before
.
    # update choice 3 as follows.
    elif choice == "3":
        score = int(input("Remove which score?: "))
        remove_score(score, scores)

To pass the tests you can just run the original program, however, you should try and write functions for the other choices. It is good practice. It will also aid your understanding of decomposition and abstraction in the next unit.