Reputation: 13
I'm a beginner at python and I was trying to write a program to guess the letters in a word, (here I used 'coconut' ). There is no limitation for guesses. If the guess was correct each time, I want to display the position of the letter as another ( 'guess_map').
So I defined the list guess_map
with same length of the word. Then using for loop I was checking the guessed input with the word and replacing the corresponding element in the list 'guess_map'.
But then I found its not working for the letters which are repeating. For example 'c'. The code is just considering the first 'c' in the word. I don't know where I have committed mistake. Can anyone help?
word = 'coconut'
reference = list(word)
number_letters = len(reference)
guess_map = ['-']*number_letters
guess = input('Guess the letter')
for let in reference:
if let == guess:
ref_ind = reference.index(let)
guess_map[ref_ind] = guess
print(guess_map)
Upvotes: 0
Views: 594
Reputation: 39354
The mistake is in ref_ind = reference.index(let)
. This will only ever find the first occurrence, even though the loop finds all of them.
This version of your program uses enumerate
to give you the right index every time.
word = 'coconut'
reference = list(word)
final = reference[:]
number_letters = len(reference)
guess_map = ['-']*number_letters
while guess_map != final:
guess = input('Guess the letter')
for ref_ind, let in enumerate(reference):
if let == guess:
guess_map[ref_ind] = guess
print(guess_map)
print("Done")
I've taken the liberty of adding a loop which keeps you guessing until you get it right.
Upvotes: 2