pythondebuggingcontrol-flowlogic-error

Execution of 'You lost' loop in Hangman game despite winning the game on the last try


I have been trying to build a Hangman game, but I am facing a problem. The game runs fine, but every time I guess the word on my last chance, instead of the “You won!” block being executed, the “You lost! Try again” block gets executed. I have added the source code and and the output below. I am guessing that I need to use a continue or break function somewhere, but I don't know for sure.

import random

animals = """lion tiger elephant giraffe monkey zebra cheetah bear wolf gorilla
dolphin kangaroo penguin owl fox rabbit horse lionfish eagle shark"""
animals_list = animals.split()
word = random.choice(animals_list)

for _ in word:
    print("_", end=" ")
print()
print()

chances = len(word) + 2
winnings = 0
letter_guessed = ""

try:
    while chances != 0 and winnings == 0:
        chances -= 1
        print(f"Chances remaining: {chances}")

        guess = input("Guess a letter: ").lower()
        print()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single letter!")
            print()
            continue

        if guess in letter_guessed:
            print("You have already guessed that letter!")
            continue

        if guess in word:
            print("Correct!")
            print()
            letter_guessed += guess

            if letter_guessed == word:
                print("The word is", word)
                print("You won!")
                winnings += 1
            else:
                for letter in word:
                    if letter in letter_guessed:
                        print(letter, end=" ")
                    else:
                        print("_", end=" ")
                print()
        else:
            print("Wrong guess!")
            print()
            letter_guessed += guess

    if chances == 0 and letter_guessed != word and winnings == 0:
        print("You lost!")
        print("Better luck next time!")
        print("The word was", word)

except KeyboardInterrupt:
    print()
    print("Bye! Try again, please!")

I got this as output:


Chances remaining: 4
Guess a letter: g

Wrong guess!

Chances remaining: 3
Guess a letter: d

Wrong guess!

Chances remaining: 2
Guess a letter: f

Correct!

f _ _ 
Chances remaining: 1
Guess a letter: o

Correct!

f o _ 
Chances remaining: 0
Guess a letter: x

Correct!

f o x 
You lost!
Better luck next time!
The word was fox

Solution

  • Change

    letter_guessed = ""
    

    To

    letter_guessed = set()
    

    And then change

    letter_guessed += guess
    

    To

    letter_guessed.add(guess)
    

    Here is the full code

    import random
    
    animals = """lion tiger elephant giraffe monkey zebra cheetah bear wolf gorilla
    dolphin kangaroo penguin owl fox rabbit horse lionfish eagle shark"""
    animals_list = animals.split()
    word = random.choice(animals_list)
    for _ in word:
        print("_", end=" ")
    print()
    print()
    
    chances = len(word) + 2
    winnings = 0
    letter_guessed = set()
    
    
    try:
        while chances != 0 and winnings == 0:
            chances -= 1
            print(f"Chances remaining: {chances}")
    
            guess = input("Guess a letter: ").lower()
            print()
    
            if len(guess) != 1 or not guess.isalpha():
                print("Please enter a single letter!")
                print()
                continue
    
            if guess in letter_guessed:
                print("You have already guessed that letter!")
                continue
    
            if guess in word:
                print("Correct!")
                print()
                for _ in  range(word.count(guess)):
                    letter_guessed.add(guess)
    
                if letter_guessed == set(word):
                    print("The word is", word)
                    print("You won!")
                    winnings += 1
                else:
                    for letter in word:
                        if letter in letter_guessed:
                            print(letter, end=" ")
                        else:
                            print("_", end=" ")
                    print()
            else:
                print("Wrong guess!")
                print()
    
        if chances == 0 and letter_guessed != word and winnings == 0:
            print("You lost!")
            print("Better luck next time!")
            print("The word was", word)
    
    except KeyboardInterrupt:
        print()
        print("Bye! Try again, please!")
    
    

    The Problems in you code

    1. You are adding guess in letter_guess even it is wrong guess

    Here

    else:
        print("Wrong guess!")
        print()
        letter_guessed += guess # here so (I have remove it)
    
    1. Your code adds only one guess letter even if there are multiply guess letter in word

    Example:

    word = "apple"
    # and the user guess 'p', then in letter_guess you have to add `p` two times but your code only adding it one time