1

I am making a hangman game in python. I use this code to check whether the input is in the word and update a list display to show known letters:

if guess in word:
    if guess not in display:
        for a in word_sliced:
            print(a)
            if a == guess:
                location = word_sliced.index(a)
                display[location] = guess
            else:
                continue
    else:
        print("guess already used!")
else:
    print("Oh no! Its not in the word!")
    health -= 1

The problem is that only one letter will be matched. For example, if the word is book and the user first guesses o, display will become ['_', 'o', '_', '_'] instead of the desired ['_', 'o', 'o', '_'].

How can I fix the code so that all the repeated letters are updated?

petezurich
  • 9,280
  • 9
  • 43
  • 57
  • what is word_sliced? – Emi OB Oct 13 '22 at 06:34
  • I'd expect that you have to show all the characters in the word, not one. The `list.index` method only returns the first match. – vahvero Oct 13 '22 at 06:35
  • 1
    Welcome to Stack Overflow. This is an extremely common problem - `.index` *searches* the list for the *first* appearance of the value passed to it (here, `a`). It has no way to know about the enclosing `for` loop, so it can't give you indices for all of the matches of the letter, and gives the same index multiple times. Please see the linked duplicate to understand how to work around this. While I have your attention, please read [ask], and note the [edit]s I made to your question in order to show proper style for Stack Overflow: this is **not a discussion forum**. – Karl Knechtel Oct 13 '22 at 06:36
  • Welcome! See this answer how to get multiple indices for the same item: https://stackoverflow.com/a/6294205/598599 use that to update `display` – AutomatedChaos Oct 13 '22 at 06:37
  • 2
    @cherrywoods that first bit isn't true, as it's nested within the if, it'll only check once so that's not the proble. The .index bit sounds like the issue – Emi OB Oct 13 '22 at 06:40

0 Answers0