Hangman Game in Python
Learning Python becomes far more interesting when you build something interactive instead of only writing theory-based programs. One of the most popular beginner-friendly projects is the Hangman game in Python. It helps you understand core programming concepts while creating a fun, playable game using simple logic.
In this article, you’ll learn how to build a complete Hangman game using Python, understand the logic step by step, and see how basic programming concepts work together in a real project. This project is perfect for Python beginners, students, and coding enthusiasts.
What Is the Hangman Game?
Hangman is a classic word-guessing game. The computer selects a secret word, and the player tries to guess it letter by letter. Every wrong guess brings the player closer to losing the game. The goal is to guess the entire word before running out of allowed attempts.
In a Python version of Hangman, the same concept applies, but instead of drawing on paper, we use code logic, loops, and conditions to control the game flow.
Why Build a Hangman Game in Python?
This project helps beginners understand important Python concepts such as variables, loops, conditional statements, lists, strings, functions, and user input handling. It also introduces the idea of game logic and state management.
By the end of this project, you’ll clearly understand how Python programs interact with users and respond dynamically to their inputs.
Concepts Used in This Project
Before diving into the code, let’s briefly understand the concepts involved.
We are using Python strings to store the secret word, lists to track guessed letters, loops to keep the game running until it ends, conditional statements to check correct or incorrect guesses, and basic input/output functions to interact with the player.
This project does not require any external libraries, making it ideal for beginners.
Step-by-Step Logic of the Game
The game follows a simple flow. First, the program selects a secret word from a predefined list. Then it displays blanks for each letter in the word. The player guesses one letter at a time. If the letter exists in the word, it is revealed in the correct position. If the letter is wrong, the number of remaining attempts decreases. The game ends when the player either guesses the word correctly or runs out of attempts.
import random
def hangman():
words = ["python", "developer", "coding", "machine", "learning", "program"]
secret_word = random.choice(words)
guessed_letters = []
attempts = 6
print("Welcome to Hangman Game!")
print("Guess the word letter by letter.")
while attempts > 0:
display_word = ""
for letter in secret_word:
if letter in guessed_letters:
display_word += letter + " "
else:
display_word += "_ "
print("\nWord:", display_word.strip())
if "_" not in display_word:
print("🎉 Congratulations! You guessed the word correctly.")
break
guess = input("Enter a letter: ").lower()
if not guess.isalpha() or len(guess) != 1:
print("Please enter a single valid letter.")
continue
if guess in guessed_letters:
print("You already guessed that letter.")
continue
guessed_letters.append(guess)
if guess not in secret_word:
attempts -= 1
print(f"Wrong guess! Attempts left: {attempts}")
else:
print("Good guess!")
if attempts == 0:
print("\n❌ Game Over!")
print("The word was:", secret_word)
hangman()
Output:

Explanation of the Code
The program starts by importing the random module to select a word randomly from a predefined list. This makes the game different every time it runs.
The hangman() function contains the entire game logic. We store the secret word, track guessed letters using a list, and define a limited number of attempts.
Inside the loop, the program displays the word using underscores for unguessed letters. If all letters are guessed correctly, the game ends with a success message.
The player is prompted to enter one letter at a time. The program checks if the input is valid and whether the letter has already been guessed. If the guess is incorrect, the number of attempts decreases.
The game ends when either the word is guessed or all attempts are used.
Real-World Learning Benefits
This project helps beginners understand how real applications work behind the scenes. It improves logical thinking, strengthens understanding of loops and conditions, and builds confidence in writing Python programs independently.
Many developers start their coding journey with small projects like Hangman before moving to advanced topics such as web development, data science, or artificial intelligence.
How You Can Improve This Game
Once you understand the basic version, you can enhance it further by adding ASCII art for the hangman figure, allowing the player to choose difficulty levels, loading words from a file, or turning the game into a GUI application using Tkinter.
These improvements help you practice advanced Python concepts while building on the same foundation.
import tkinter as tk
word = "python"
guessed = []
def guess_letter():
letter = entry.get().lower()
if letter not in guessed:
guessed.append(letter)
display = ""
for l in word:
display += l if l in guessed else "_"
label.config(text=display)
entry.delete(0, tk.END)
root = tk.Tk()
root.title("Hangman Game")
label = tk.Label(root, text="______", font=("Arial", 24))
label.pack(pady=20)
entry = tk.Entry(root, font=("Arial", 14))
entry.pack()
button = tk.Button(root, text="Guess", command=guess_letter)
button.pack(pady=10)
root.mainloop()

Advance Version:
import random
import time
# Initial Steps to invite in the game:
print("\nWelcome to Hangman game by DataFlair\n")
name = input("Enter your name: ")
print("Hello " + name + "! Best of Luck!")
time.sleep(2)
print("The game is about to start!\n Let's play Hangman!")
time.sleep(3)

import random
import time
# Welcome Message
print("\nWelcome to Hangman Game\n")
name = input("Enter your name: ")
print(f"Hello {name}! Best of Luck!")
time.sleep(1)
print("The game is about to start...\nLet's play Hangman!")
time.sleep(1)
# Global Variables
word = ""
display = ""
already_guessed = []
attempts = 0
max_attempts = 5
# ASCII Hangman Stages (FIXED BACKSLASHES)
def show_hangman(attempts):
stages = [
"""
_____
| |
| |
| |
| O
| /|\\
| / \\
__|__
""",
"""
_____
| |
| |
| |
| O
| /|\\
|
__|__
""",
"""
_____
| |
| |
| |
| O
|
|
__|__
""",
"""
_____
| |
| |
| |
|
|
|
__|__
""",
"""
_____
|
|
|
|
|
|
__|__
""",
""
]
print(stages[attempts])
# Initialize Game
def init_game():
global word, display, already_guessed, attempts
words = [
"python", "coding", "hangman", "developer",
"program", "logic", "keyboard", "computer"
]
word = random.choice(words)
display = "_" * len(word)
already_guessed = []
attempts = 0
# Play Again Loop
def play_again():
choice = input("\nDo you want to play again? (y/n): ").lower()
if choice == "y":
init_game()
play_game()
else:
print("\nThanks for playing! See you again 👋")
exit()
# Main Game Logic
def play_game():
global display, attempts
while attempts < max_attempts and "_" in display:
print("\nWord:", display)
guess = input("Enter a letter: ").lower().strip()
if len(guess) != 1 or not guess.isalpha():
print("❌ Invalid input. Enter a single letter.")
continue
if guess in already_guessed:
print("⚠️ You already guessed that letter.")
continue
already_guessed.append(guess)
if guess in word:
for i in range(len(word)):
if word[i] == guess:
display = display[:i] + guess + display[i + 1:]
print("✅ Good guess!")
else:
attempts += 1
print("❌ Wrong guess!")
show_hangman(attempts)
print(f"Remaining attempts: {max_attempts - attempts}")
# Result
if "_" not in display:
print("\n🎉 Congratulations! You guessed the word:", word)
else:
print("\n💀 Game Over! The word was:", word)
play_again()
# Start Game
init_game()
play_game()

Who Should Try This Project?
This Hangman game project is ideal for Python beginners, school and college students, self-learners, and anyone preparing for programming interviews. It’s also a great addition to your GitHub portfolio as a beginner project.
Final Thoughts
The Hangman Game in Python is a perfect beginner project that combines fun and learning. It teaches essential Python concepts in a practical way while keeping the learning process engaging. If you’re starting your Python journey, building projects like this will significantly improve your confidence and problem-solving skills.





Leave a Reply