tags:

views:

90

answers:

2

Hey,

I've just started to learn Python and I'm creating the game Hangman. I've got the basic functionality down. I have a list containing the words and they're randomly selected. I have an input for the user to guess letters and check it against the list that the word is split into, I have another list that the correctly guessed letters are put into at the position they are in the randomly selected word.

The problem I am having is that if the word has a letter within it more than once, it will only find the first letter and add that. How would I go about looking for all instances of a letter and adding them?

This is the code I'm using to map guessed letters against the randomly selected word.

if user_input in choose_word:
    print "Good guess!"
    print trys_remaining, "trys remaining!"
    word_index = letter_list.index(user_input)
    correct_letters[word_index] = user_input

If anyone could point me in the right direction, it would be great.

+4  A: 

You need to loop over all matching indices:

for word_index, letter in enumerate(letter_list):
    if letter == user_input:
        correct_letters[word_index] = user_input

Note: If the loop would be for letter in letter_list: you would only iterate over letters but won't get the corresponding index. The enumerate() function allows to get the index at the same time. See also the enumerate documentation.

catchmeifyoutry
That is fantastic, thanks so much for the quick reply.
Curt Walker
Quick update, it's working perfectly, thanks so much for the help.
Curt Walker
That's pretty perfect. Maybe add case sensitivity by `lower`-ing `user_input` and `letter`.
jellybean
A: 

You can use a list comprehension:

correct_letters = [letter if user_input == letter else correct
                   for (correct, letter) in zip(correct_letters, letter_list)]

Note that this will create a new correct_letters list, instead of modifying the original one.

Xavier Martinez-Hidalgo