Hangman Game using Python

Hangman Game using Python

Oct 10, 2022ยท

6 min read

Play this article


According to Wikipedia,

Hangman is a paper and pencil guessing game for two or more players. One player thinks of a word, phrase or sentence and the other tries to guess it by suggesting letters within a certain number of guesses.

If you haven't played the game, you can play it here.

In this blog, we're going to build the Hangman game using Python. This is a beginner-friendly project and can help beginners boost their programming skills and logic.


If the video doesn't work properly, watch it here.

How It Works

  • First of all, a word is selected randomly from a secret list of words. For this, we'll be using Python's in-built random module.
  • The player gets a limited number of chances(in our case, 6) to guess the word correctly. The chances left are represented in the form of a hanging man.
  • When a letter of the word is guessed correctly, the letter position is made visible.

Let's Code It

To give visual appeal to the players, we'll create figures of the hanging man for each stage, i.e., whenever a life is lost, the figure will change.

Create a hangman_art.py file and add the following content there:

stages = ['''
  | |
  O |
 /|\ |
 / \ |
''', '''
  | |
  O |
 /|\ |
 / |
''', '''
  | |
  O |
 /|\ |
''', '''
  | |
  O |
 /| |
=========''', '''
  | |
  O |
  | |
''', '''
  | |
  O |
''', '''
  | |

logo = '''
| |
| | ____ _ _ ____ _ _ _____  ___ ___
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\ __,_|_| |_|\__ , |_| |_| |_|\__,_|_| |_|
                    __/ |
                   |___/ '''

We've created a list called stages where we have put each figure. Apart from that, we have a Hangman logo too, that we'll show when the game starts.

Next, we'll create our secret list of words from where our program will select words randomly. Create a hangman_words.py file and the following content there:

word_list = [

We have created a Python list called words_list in the above code.

Now we have the main task left, i.e. writing the logic for the Hangman game. Create a hangman.py file and add the following code to it.

import random
from hangman_art import stages, logo
from hangman_words import word_list

def hangman_game(chosen_word):
    end_of_game = False

    lives = len(stages) - 1

    guessed_letters = []
    for _ in range(len(chosen_word)):
        guessed_letters += "_"

    while not end_of_game:
        guess = input("Guess a letter: ").lower()

        if guess in guessed_letters:
            print(f"You've already guessed {guess}")

        for position in range(len(chosen_word)):
            letter = chosen_word[position]
            if letter == guess:
                guessed_letters[position] = letter
        print(f"{' '.join(guessed_letters)}")

        if guess not in chosen_word:
            print(f"You guessed {guess}, that's not in the word. You lose a life.")
            lives -= 1
            if lives == 0:
                end_of_game = True
                print("You lose.")
                print(f"The word was {chosen_word}.")

        if not "_" in guessed_letters:
            end_of_game = True
            print("You win.")


if __name__ == " __main__":
    chosen_word = random.choice(word_list)
    print(f"It is a {len(chosen_word)}-letters word.")

At first, we have imported the random library from Python which will be required to select random words. Also, we have imported stages and logo from the hangman_art.py file and words_list from the hangman_words.py file respectively.

Let's look at the hangman_game() function now. This function accepts an argument chosen_word, i.e., the randomly selected word. Inside the function, we have a variable end_of_gamethat determines whether the game should continue or not. Next, we have a lives variable which has a value oflen(stages)-1, i.e., 6. In the beginning, we show the users blanks() according to the length of the word chosen. We have a list called guessed_letters to store the letters guessed correctly by the user. Initially, it contains underscores() equal to the number of letters in the word. Gradually, these underscores will be replaced with the correct letters guessed by the player.

After that, we start a while loop till the end_of_game, and ask the user to make a guess. If the guess is already in the guessed_letters list, we do not reduce the life and ask the user to guess again. We run a for loop over the chosen word to see if the user has guessed a correct letter, we would make it visible and add it to the guessed_letters list on its correct index/indices. If the guessed letter is not in the chosen word, we reduce the lives variable by 1. At this instance, we also check if the lives is equal to 0, we set the end_of_game variable to True so that the game doesn't continue anymore. The user has lost the game and we tell the user the correct word. Also if no underscores(_), i.e., blank spaces are left in the guessed_letters, we set the end_of_game variable to True, but this time, the user has won the game. After each guess, we print the figure of our hangman.

In the main method, we first print the Hangman logo as we mentioned earlier. Next, we select a random word. We then tell the user the number of letters in the word that needs to be guessed. After that, we run the hangman_game() function and the game starts.

Wrapping Up

In this blog, we've built the Hangman game using Python. Hope you found the tutorial helpful.

Did you find this article valuable?

Support Ashutosh Krishna by becoming a sponsor. Any amount is appreciated!