Hangman Issue: How do I make my loop reset when the letter entered is not present and how do I make the letter appear more than once in the word?

Question:

The word_chosen is "apple". However, when I enter the letter p, it only appears once in the word. I would also like to make my loop reset when the letter entered is not correct.

def guesses():
  guess = 0
  hangman_word = "_____"
  while guess < 5:
    guess_player = input("What is your letter? ")
    for i in range(len(word_chosen)):
        if guess_player == word_chosen[i]:
            guess_player = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
            print(guess_player)
            continue
        elif guess_player != word_chosen[i]:
            guess += 1
Asked By: Prognoob2

||

Answers:

Some issues:

  • The following assignment is wrong:

    guess_player = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
    

    You should not update guess_player which is the input letter. Instead you should update hangman_word. So:

    hangman_word = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
    
  • The following condition will always be true when the execution gets there:

    elif guess_player != word_chosen[i]:
    

    The opposite was already checked in the preceding if statement, so the only possibility left is that the guess was wrong. No need to test that again.

  • guess += 1 should not appear within the loop. If the guess does not match the first letter, that doesn’t mean it cannot still match with the second letter. So it is wrong to increment this counter when the comparison has not yet been made with all remaining letters of the secret word.

    You can make use of the in operator to check whether there is at least one occurrence of the guessed letter:

    if guess_player in word_chosen:
        # ... here comes your loop to update `hangman_word` ... (without `elif`)
    else:
        guess += 1
    
  • The while loop should exit not only when the player has made five wrong guesses, but also if the player has found the word! You can do that as follows:

    while guess < 5 and "_" in hangman_word:
    
  • When the while loop exits, you should probably report on the outcome of the game. Was it a success or not? It could be:

    if "_" in hangman_word:
        print("You guessed 5 times wrong. Game over.")
    else:
        print("You guessed the word. Well done!")
    
  • There should probably be some message when the player repeats a good guess a second time (optional).

Here is your code with corrections for the above points:

def guesses():
    guess = 0
    hangman_word = "_____"
    while guess < 5 and "_" in hangman_word:
        guess_player = input("What is your letter? ")
        if guess_player in hangman_word:
            print("But...but... you already guessed that letter!?")
        elif guess_player in word_chosen:
            print("Good going!")
            for i in range(len(word_chosen)):
                if guess_player == word_chosen[i]:
                    hangman_word = (hangman_word[:i]) + word_chosen[i] + hangman_word[i + 1:]
        else:
            print("That letter does not occur in the word.")
            guess += 1
        print(hangman_word)

    if "_" in hangman_word:
        print("You guessed 5 times wrong. Game over.")
    else:
        print("Well done!")
Answered By: trincot

A couple aspects of the code can be improved.

def guesses():
    # PreEnter the word for referece
    word_chosen = "hangman"
    
    guess = 0
    
    # Creating a list instead of a string, to be able to update it, rather than creating new ones.
    hangman_word = ["_" for _ in range(len(word_chosen))]
    
    # Storing entered letters in a list for fair play in case wrong letters are entered.
    entered_letters = []

    while guess < 5:
        guess_player = input("Enter a Letter: ")

        # Checking if enterd string contains a single letter
        if len(guess_player) > 1:
            print("You can only enter one letter at a time.")
            continue

        if guess_player in entered_letters:
            print("You already guessed that letter")
            continue
        
        # Using for loop only after checking if the letter is in the word.
        elif guess_player in word_chosen:
            for i in range(len(word_chosen)):
                if guess_player == word_chosen[i]:
                    hangman_word[i] = guess_player
            
        else:
            print("That was an incorrect choice!")
            guess += 1

        # appending the entered letter to the list of entered letters.
        entered_letters.append(guess_player)

        # Using "".join to print the string from the list.
        word = "".join(hangman_word)
        print(word)

        # Checking if the word is complete.
        if word == word_chosen:
            return "You Win!"
    
    # If the player runs out of guesses, the game is over.
    return "You Lose!"

print(guesses())

Since you are a beginner, try understanding the code through comments and see if you can figure out which aspects of your code I altered. Feel free to point out anything you have doubts about.

Answered By: Argish Abhangi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.