Python Hangman Game

Geekedu is an expert in Coding and Math learning. Our goal is to inspire and empower youth to use their knowledge of technology to become the influencers, inventors and innovators of the future.

Table Of Content:

Introduction: 

In this article, we are going to be using Python to create a simple Hangman game. This program will ask users to guess a word, and if they get more than 5 answers wrong, they lose..

Python Hangman Game

This project is a great way to learn more about making functional programs by creating a functional and versatile program. It’s a great way to build both your creative thinking and problem-solving skills while making a fun and entertaining game as well!

Who is this Project For?

This is an intermediate-level project for those who are new to Python, or those who want a fun way to apply their coding skills. Before starting this project, you should have some experience with creating and using functions, loops, and conditional statements such as if-statements. These concepts are widely used in any computer program, and your knowledge of these concepts will be developed as you work through this project.

What Will We Learn?

This program focuses on creating a functional Hangman game that users can play on their own or with friends. This teaches concepts such as if-statements, functions, and using operators as well as other essential programming concepts.

Features to Consider:

  • The user will be given a word to guess
  • They are allowed to guess letters, if they get the letter correct it is revealed
  • If the player guesses once, their player is drawn on the screen
  • If the player gets 5 incorrect guesses, the player has lost and the game is over.

Pseudo Code:

The pseudocode for this project is included below:

Import the time and random library
Function main():
	Create global variables for count, display, word, already_guessed, length, and play_game
	Create a list of words to guess
	Pick a random word from the list
	Set length to the length of the word
	Set count to 0
	Set display to as many underscores as the word is long
	Create an empty list called already_guessed
Function hangman():
	Access the global variables for count, display, word, already_guessed, and play_game
	Set limit to 5
Ask the user for input
Strip the input, and if it is not a valid letter, let the player know to try again
Otherwise, check if the letter is in the word
If so:
	Reveal that letter in the displayed word
	Ask the player to guess another letter
Else: 
	Print the hangman diagram (this will differ based on the number of incorrect
guesses)
If the full word is revealed:
	Print (congratulations!
Else:
	Call the hangman() function
Run the main function
Run the hangman function
Python Hangman Game

Main Steps:

This project can be broken down into 3 main steps: 

  1. Create the main function
  2. Check user input
  3. Complete the hangman function

Step 1: Create the Main Function

The first thing we’ll need to do when creating this program is to import the time library. This will allow the program to manage any delay the program may have. We will also import the random module, which will be used to randomly select a word for the game.

import random
import time

Then, we’ll need to create our main function, which will involve creating variables and setting up a list of possible words for the player to guess..

def main():
    global count
    global display
    global word
    global already_guessed
    global length
    global play_game
    words_to_guess = ["code", "geekedu", "hello", "computer", "robot", "python"]
    word = random.choice(words_to_guess)
    length = len(word)
    count = 0
    display = '_' * length
    already_guessed = []
    play_game = ""
Python Hangman Game

Step 2: Check for User Input

Next, we need to create the Hangman function to ask for user input. We will begin this function by referencing many of the global variables that we created in the main function, and then we will ask the user for their input. This code will be done like so:

def hangman():
    global count
    global display
    global word
    global already_guessed
    global play_game
    limit = 5
    guess = input("Your word is: " + display + " Enter your guess: \n")

Now we need to take this input and check if it is valid. We will do this by first checking whether it is a single letter, and then checking whether it is in the word that the player has to guess. This is the rest of the code for this step:

 guess = guess.strip()
    if len(guess.strip()) == 0 or len(guess.strip()) >= 2 or guess <= "9":
        print("Invalid Input, Try a letter\n")
        hangman()

    elif guess in word:
        already_guessed.extend([guess])
        index = word.find(guess)
        word = word[:index] + "_" + word[index + 1:]
        display = display[:index] + guess + display[index + 1:]
        print(display + "\n")
    elif guess in already_guessed:
        print("Try another letter.\n")

As you can see, we now have created some code that will control whether or not the input is valid, and if it is, this code will reveal a letter.

Python Hangman Game

Step 3: Complete the Hangman Function

Finally, we need to print the hangman illustrations that will be shown if the user guesses a wrong letter. While this section of code is quite long, it is repetitive, so once you complete one section, the rest will be easy to quickly add in. This is the final section of code for this project, and it is as follows:

else:
        count += 1
        if count == 1:
            time.sleep(1)
            print("   _____ \n"
                  "  |      \n"
                  "  |      \n"
                  "  |      \n"
                  "  |      \n"
                  "  |      \n"
                  "  |      \n"
                  "__|__\n")
            print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
        elif count == 2:
            time.sleep(1)
            print("   _____ \n"
                  "  |     | \n"
                  "  |     |\n"
                  "  |      \n"
                  "  |      \n"
                  "  |      \n"
                  "  |      \n"
                  "__|__\n")
            print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
        elif count == 3:
           time.sleep(1)
           print("   _____ \n"
                 "  |     | \n"
                 "  |     |\n"
                 "  |     | \n"
                 "  |      \n"
                 "  |      \n"
                 "  |      \n"
                 "__|__\n")
           print("Wrong guess. " + str(limit - count) + " guesses remaining\n")
        
        elif count == 4:
            time.sleep(1)
            print("   _____ \n"
                  "  |     | \n"
                  "  |     |\n"
                  "  |     | \n"
                  "  |     O \n"
                  "  |      \n"
                  "  |      \n"
                  "__|__\n")
            print("Wrong guess. " + str(limit - count) + " last guess remaining\n")
        elif count == 5:
            time.sleep(1)
            print("   _____ \n"
                  "  |     | \n"
                  "  |     |\n"
                  "  |     | \n"
                  "  |     O \n"
                  "  |    /|\ \n"
                  "  |    / \ \n"
                  "__|__\n")
            print("Wrong guess. You are hanged!!!\n")
            print("The word was:",already_guessed,word)
    if word == '_' * length:
        print("Congrats! You have guessed the word correctly!")
    elif count != limit:
        hangman()
main()
hangman()

You will notice that at the bottom of this code we also included a message for when the player loses the game, as well as an if-statement to congratulate them if they guess the word correctly. We also called the main and hangman functions at the end of the code in order to run the game.

Project Complete!

Python Hangman Game

Now the project is complete! We hope that you’ve enjoyed creating this fun and simple hangman game. Feel free to test your code out and check the code mentioned above as a reference if you have any errors.

Geek Team

Sign up and get a 60-minute free assessment class

Book A FREE Trial