Python Forum

Full Version: Python Hangman Game - Multiple Letters Problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Python 3.6.5

I've created a hangman game in Python and I'm trying to debug an error:

The game works in a way that randomly picks a word from a list, stars out the word (using two separate variable names), and then each time a letter is guessed correctly, the star is replaced with the correct letter in the correct position. However, for instance the word "seen". If you correctly guess the letter "e" it will populate the guess as *e**. It will not add two e's. This is because I'm using the .find() function, which stops after finding the correct letter:
if guess in full_word: #replacing the * in selected_word with the guessed letter that was correct
             checker = full_word.find(guess)
             selected_word = selected_word[:checker] + guess + selected_word[checker+1:]
can anyone offer any advice that allows the program to check multiples of the same letter?

thank you!
The find function returns the index of the first instance found. That's why it stops working after the first one is found. If it doesn't find an instance then it returns -1. What you need to do is keep running find in a loop until it returns -1.
Something like:
while full_word.find(guess):
    selected_word = selected_word[:checker] + guess + selected_word[checker+1:]
(Jun-04-2020, 02:26 PM)Clunk_Head Wrote: [ -> ]The find function returns the index of the first instance found. That's why it stops working after the first one is found. If it doesn't find an instance then it returns -1. What you need to do is keep running find in a loop until it returns -1.
Something like:
while full_word.find(guess):
    selected_word = selected_word[:checker] + guess + selected_word[checker+1:]

I'm not getting this to work. Wouldn't it still just have the same problem? full_word is the original word, and selected_word is the starred out version. If I just keep running .find on full_word with guess, surely it would still keep ending at the first index?
I instead of using find, why not compare each letter? I did that here:

https://python-forum.io/Thread-else-cond...#pid111183
Thank you! This worked. :)