Black Friday Sale: Get 50% Off on First Month Fee For All Courses* - Claim your spot now!
Coding

How to Make a Hangman Game in Python: A Step-by-Step Guide

Reading Time: 8 mins

Image6

Creating a Hangman game in Python is an engaging way to strengthen your programming skills while building a fun project. This guide will walk you through the process step by step, providing clear explanations and practical examples. Whether you’re a beginner or looking to refresh your skills, this project introduces essential coding concepts in an approachable way.

What is a Hangman Game?

Hangman is a classic word-guessing game where players try to reveal a hidden word by guessing one letter at a time. Each incorrect guess brings the player closer to losing, as a visual representation of a hangman gradually forms. The game is simple to understand, yet it provides ample opportunities to practice programming logic, loops, and user input handling.

By building a Hangman game in Python, you’ll gain hands-on experience with fundamental coding techniques, such as string manipulation, conditional statements, and loops.

Image6

Why Build a Hangman Game in Python?

Python’s straightforward syntax makes it a great choice for beginners and hobbyists alike. Developing a Hangman game not only solidifies your understanding of basic programming concepts but also teaches you how to structure a project logically. Through this project, you’ll explore topics such as:

  • Organising and processing data efficiently.
  • Implementing user interaction and input validation.
  • Creating modular code that can be easily expanded or debugged.

This project is a stepping stone toward building more complex applications, making it an excellent starting point for anyone learning Python.

What You Need Before You Begin?

Before diving into the code, ensure that you have:

  1. Python Installed: Download and install the latest version of Python (3.x or higher) from python.org.
  2. An IDE or Text Editor: Use an environment like PyCharm, Visual Studio Code, or even IDLE for writing and testing your code.
  3. Basic Python Knowledge: Familiarity with variables, loops, functions, and conditionals will help you follow along.

Having these tools and a basic understanding of Python sets you up for success as you begin coding your Hangman game.

Step 1: Setting Up Your Development Environment

The first step is to prepare your workspace:

  1. Open your IDE or text editor.
  2. Create a new Python file named hangman.py.

Verify that Python is installed correctly by running a simple command in the terminal:
python –version

  1.  If Python is installed, this command will display the version number.

Once your environment is ready, you can start writing the code.

Step 2: Creating a flowchart for the game logic:

Image7

Step 3: # ASCII art for different stages of the hangman

hangman_stages = [
    '''
     +---+
     |   |
         |
         |
         |
         |
    =========
    ''',
    '''
     +---+
     |   |
     O   |
         |
         |
         |
    =========
    ''',
    '''
     +---+
     |   |
     O   |
     |   |
         |
         |
    =========
    ''',
    '''
     +---+
     |   |
     O   |
    /|   |
         |
         |
    =========
    ''',
    '''
     +---+
     |   |
     O   |
    /|\  |
         |
         |
    =========
    ''',
    '''
     +---+
     |   |
     O   |
    /|\  |
    /    |
         |
    =========
    ''',
    '''
     +---+
     |   |
     O   |
    /|\  |
    / \  |
         |
    =========
    '''
]

Step 4: Creating a Word Bank

The word bank serves as the foundation for your game. It contains a list of words that players will attempt to guess. To create a simple word bank:

For added variety, you can import words from an external Python file(hangman_words.py):

import hangman_words

list_words = ["apple","potato","ginger","movie","car","race","Python","coding","program"]
Image2

This approach makes it easy to expand your word bank without modifying the code directly.

Step 5: Writing the Core Game Logic

The game logic determines how the Hangman game operates. Begin by selecting a random word for the player to guess:

import random
ran_word = random.choice(hangman_words.list_words)
Image1

Initializing Variables

lives = 6
print(ran_word)  # This line can be removed if you don't want to reveal the word
placeholder = "-" * len(ran_word)
print(placeholder)
  • The player starts with 6 lives (which equals 6 incorrect guesses).
  • placeholder is a string of dashes (), where each dash represents an unrevealed letter of the randomly selected word. The number of dashes is equal to the length of the word.
  • For example, if the word is “apple,” placeholder will initially be “—–“.
  • The line print(ran_word) is optional and only used for debugging purposes (showing the word). In an actual game, this would be hidden.

Game Variables

game_over = False
correct_letters = []  # List of correctly guessed letters
incorrect_letters = []  # List of incorrectly guessed letters
  • The game_over flag controls when the game should end. It is initially set to False.
  • correct_letters is an empty list where correctly guessed letters will be stored.
  • incorrect_letters is another empty list for storing incorrectly guessed letters.
Image4

Step 6:  Main Game Loop

while not game_over:
  • The game loop continues as long as game_over remains False. Each iteration allows the player to guess one letter.

Step 7: Player Input

letter = input("Guess a letter: ").lower()
  • The player is prompted to input a guess (a single letter). The input() function captures this input, and lower() converts it to lowercase to ensure case-insensitive matching.

Step 8: Checking If the Letter Was Already Guessed

if letter in correct_letters or letter in incorrect_letters:
   print(f"You already guessed '{letter}'. Try a different letter.")
   continue  # Skip the rest of the loop to avoid processing this letter
again
  • This checks if the player has already guessed the letter (either correctly or incorrectly). If so, the game reminds the player that the letter has been guessed and asks them to guess a new one. The continue statement skips to the next iteration of the loop without further processing.               

Step 9: Processing a Correct Guess

display = ""
    if letter in ran_word:
        correct_letters.append(letter)  # Track correct guesses
        for i in ran_word:
            if i in correct_letters:
                display += i
            else:
                display += "-"
  • If the guessed letter is in the ran_word (the word to be guessed):
    1. The letter is added to the correct_letters list.
    2. The loop (for i in ran_word) goes through each letter in ran_word and builds the updated word display. If a letter has been guessed (exists in correct_letters), it is revealed. Otherwise, a dash (-) is kept in its place.
    3. The new display with guessed letters and dashes is stored in the display variable.

Step 10: Processing an Incorrect Guess

    else:
        incorrect_letters.append(letter)  # Track incorrect guesses
        lives -= 1
        print(hangman_stages[6 - lives])  # Display the hangman stage corresponding to the number of lives left
        print(f"Incorrect guess. Lives left: {lives}")
        if lives == 0:
            game_over = True
            print(f"You lose! The correct word was '{ran_word}'.")
            break  # Exit the loop after showing the correct word
  • If the guessed letter is not in ran_word:
    1. The letter is added to the incorrect_letters list.
    2. The player loses one life (lives -= 1).
    3. The current stage of the hangman is displayed using ASCII art. The stage is selected from the list hangman_stages, where the index is determined by how many lives are remaining.
    4. If lives reach 0, the game ends, and the correct word is revealed. The game breaks out of the loop and terminates.
Image5

Step 11:Updating and Displaying the Word

print(display)
Image3
  • The updated word display, including any correctly guessed letters and unrevealed dashes, is printed after each guess.

Step 12: Checking for a Win

if "-" not in display:
        game_over = True
        print("Congratulations, you win!")
Image8
  • If the display no longer contains any dashes (-), it means that the player has successfully guessed the entire word.
  • The game ends with a win message.

Enhancing the Gameplay

To make the game more engaging, you can add features like:

  • Tracking Incorrect Guesses: Keep a record of letters the player has already guessed.
guessed_letters = set()
if guess in guessed_letters:
print("You already guessed that letter!")
guessed_letters.add(guess)
  • Dynamic Word Selection: Use different word categories, such as animals or countries, to increase replayability.

Testing and Debugging Your Game

Before sharing your Hangman game, test it thoroughly:

  1. Edge Cases: Handle situations like empty guesses, repeated letters, and special characters.
  2. Debugging: Use print() statements to verify variable values and logic flow.
  3. Game End Conditions: Ensure the game ends correctly when the player wins or loses.

Common Challenges and Solutions

As you build your Hangman game, you might encounter some challenges:

  • Handling Case Sensitivity: Convert all inputs and the chosen word to lowercase to avoid mismatches.
  • Avoiding Infinite Loops: Double-check your loop conditions to ensure the game progresses correctly.

Validating Input: Prompt users to enter only single letters:

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

These solutions help create a smoother and more enjoyable user experience.

Frequently Asked Questions

1. Is Hangman a good project for beginners?
 Yes, Hangman is an excellent project for learning programming fundamentals. It covers key topics like loops, conditionals, and input handling while being simple enough for beginners to understand.

2. How can I share my Hangman game with friends?
 You can package your Python script into an executable file using tools like PyInstaller. This makes it easy for others to run the game without needing Python installed.

3. Can I add more features to the game?
 Absolutely! Consider adding a scoring system, difficulty levels, or multiplayer functionality to make the game more exciting.

Conclusion

Building a Hangman game in Python is both fun and educational. It allows you to practise essential programming skills while creating something tangible and interactive. With this guide, you’ve learned how to set up your environment, write the game logic, and enhance it with additional features. Start coding today, and enjoy the satisfaction of seeing your project come to life!

Become a Future Tech Innovator
At ItsMyBot, we inspire children to explore coding, AI, and robotics through engaging, hands-on learning experiences. Our courses build essential tech skills, confidence, and creativity—preparing kids for a tech-driven future.

Tags

Share

Poornima Sasidharan

An accomplished Academic Director, seasoned Content Specialist, and passionate STEM enthusiast, I specialize in creating engaging and impactful educational content. With a focus on fostering dynamic learning environments, I cater to both students and educators. My teaching philosophy is grounded in a deep understanding of child psychology, allowing me to craft instructional strategies that align with the latest pedagogical trends.

Related posts