Python Programming for the Absolute Beginner, 3rd Edition
Lists have methods that allow you to manipulate them. Through list methods, you can add an element, remove an element based on its value, sort a list, and even reverse the order of a list.
Introducing the High Scores Program
The High Scores program uses list methods to create and maintain a list of the user's best scores for a computer game. The program uses a simple, menu-driven interface. The user has a few choices. He or she can add a new score, delete a score, sort the scores, or quit the program. Figure 5.6 shows the program in action.
Setting Up the Program
The setup code for the program is pretty simple. After the initial comments, I create two variables. scores is a list that will contain the scores. I set it to an empty list to start out. choice represents the user's choice from the menu. I initialized it to None.
# High Scores # Demonstrates list methods # Michael Dawson - 1/30/03 scores = [] choice = None
Displaying the Menu
The while loop is the bulk of the program. It continues until the user enters 0. The rest of this code prints the menu and gets the user's choice:
while choice != "0": print \ """ High Scores Keeper 0 - Exit 1 - Show Scores 2 - Add a Score 3 - Delete a Score 4 - Sort Scores """ choice = raw_input("Choice: ") print
Exiting the Program
I first check if the user wants to quit. If the user enters 0, the computer says "Good-bye.":
# exit if choice == "0": print "Good-bye."
If the user enters 0, then the while loop's condition will be false the next time it's tested. The loop will end and so will the program.
Displaying the Scores
If the user enters 1, then this elif block executes and the computer displays the scores:
# list high-score table elif choice == "1": print "High Scores" for score in scores: print score
Adding a Score with the append() Function
If the user enters 2, the computer asks the user for a new score and assigns it to score. The last line appends this new number to scores, which means it tacks it on to the end of the list. The list becomes one element longer.
# add a score elif choice == "2": score = int(raw_input("What score did you get?: ")) scores.append(score)
Removing a Score with the remove() Function
When the user enters 3, the computer gets a score from the user to remove. If the score is in the list, the computer removes the first occurrence of it. If the score isn't in the list, the user is informed.
# delete a score elif choice == "3": score = int(raw_input("Delete which score?: ")) if score in scores: scores.remove(score) else: print score, "isn't in the high scores list."
The computer first checks to see if the score is in the list. If so, the computer goes through the list, starting at position 0, and searches for the score. When it finds the score, that element is deleted. If the score is in the list more than once, only the first occurrence is removed. You can see how this is different from the del command. The remove() function doesn't delete an element based on a position, but rather on a value. If the score wasn't found in the list, the user is informed.
TRAP | Watch out when you use the remove() method. If you try to remove a value that isn't in a list, you'll generate an error. |
Sorting the Scores with the sort() Function
The scores in the list are in the exact order the user entered them. Normally, you want a high score list to be sorted with the highest scores at the top. To sort the scores, all the user has to do is enter 4:
# sort scores elif choice == "4": scores.sort()
The sort() method sorts the elements in the list. This is great, except that with sort(), you end up with the list in ascending order, where the smallest values are first. But what I want is the largest numbers first. I need the reverse of this.
Reversing the Scores with the reverse() Function
Luckily, there's a reverse() method for lists. It just reverses the list order. This is exactly what I need so that the highest scores will be at the beginning of the list. Before the elif block ends, I use the reverse() method, like so:
scores.reverse() # want the highest number first
Now, all the scores are in order, from largest to smallest. Perfect.
Dealing with an Invalid Choice
If the user enters a number that isn't a valid choice, the else clause catches it. The program lets the user know that the choice isn't understood.
# some unknown choice else: print "Sorry, but", choice, "isn't a valid choice."
Waiting for the User
After the user enters 0 to exit, the loop ends. As always, the program waits for the user:
raw_input("\n\nPress the enter key to exit.")
You've seen a bunch of useful list methods in action. To get a summary of these methods (plus a few more), take a look at Table 5.1.
Method | Description |
---|---|
append(value) | Adds value to end of a list. |
sort() | Sorts the elements, smallest value first. |
reverse() | Reverses the order of a list. |
count(value) | Returns the number of occurrences of value. |
index(value) | Returns the first position number of where value occurs. |
insert(i, value) | Inserts value at position i. |
pop([i]) | Returns value at position i and removes value from the list. Providing the position number i is optional. Without it, the last element in the list is removed and returned. |
remove(value) | Removes the first occurrence of value from the list. |
Категории