Build a Python Hangman Game Step by Step

A Hangman game is a practical beginner project because it uses input validation, loops, strings, lists, sets, and conditional logic in one small program. In this tutorial, we will build a command-line Hangman game in Python that chooses a secret word, tracks correct and wrong guesses, and stops when the player wins or runs out of attempts.

The main improvement over a hard-coded demo is that the word is selected from a sequence with random.choice(), which the Python documentation defines for picking an item from a non-empty sequence. We will also normalize player input with str.lower() so uppercase and lowercase guesses behave the same way.

How the Hangman Logic Works

The game needs five pieces of state:

  • secret_word: the word the player is trying to guess.
  • guessed_letters: a set of letters the player already tried.
  • wrong_guesses: how many incorrect guesses have been made.
  • max_wrong_guesses: the losing limit.
  • A loop that keeps asking for letters until the player wins or loses.

If you are new to the looping part, see Python Pool’s guide to for vs while loops in Python. For a refresher on user prompts, read Python user input.

Complete Python Hangman Code

Save this as hangman.py and run it with Python 3:

import random

WORDS = ("python", "variable", "function", "iterator", "package")


def show_progress(secret_word, guessed_letters):
    return " ".join(
        letter if letter in guessed_letters else "_"
        for letter in secret_word
    )


def play_hangman():
    secret_word = random.choice(WORDS)
    guessed_letters = set()
    wrong_guesses = 0
    max_wrong_guesses = 6

    print("Guess the word:", show_progress(secret_word, guessed_letters))

    while wrong_guesses < max_wrong_guesses:
        guess = input("Enter one letter: ").strip().lower()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter exactly one alphabet letter.")
            continue

        if guess in guessed_letters:
            print("You already tried that letter.")
            continue

        guessed_letters.add(guess)

        if guess in secret_word:
            print("Correct:", show_progress(secret_word, guessed_letters))

            if all(letter in guessed_letters for letter in secret_word):
                print(f"You won! The word was {secret_word}.")
                return
        else:
            wrong_guesses += 1
            remaining = max_wrong_guesses - wrong_guesses
            print(f"Wrong. {remaining} guesses left.")
            print(show_progress(secret_word, guessed_letters))

    print(f"You lost. The word was {secret_word}.")


if __name__ == "__main__":
    play_hangman()

Code Explanation

WORDS stores the possible answers. A tuple is fine here because the game does not need to edit the word list while it runs. If you want to select from a changing list, read randomly select from a list in Python.

show_progress() builds the masked display. For every letter in the secret word, it shows the letter if the user guessed it and an underscore otherwise. The expression is joined with spaces so the output is easier to read.

input() reads the player’s next guess. The official input() documentation explains that it reads a line from standard input and returns it as a string. The code then uses strip() to remove extra spaces and lower() to make guesses case-insensitive. Python Pool also has a separate tutorial on converting strings to lowercase in Python.

A set is used for guessed_letters because membership checks such as guess in guessed_letters are direct and readable. That lets the game reject repeated guesses before changing the score.

Example Output

Guess the word: _ _ _ _ _ _
Enter one letter: p
Correct: p _ _ _ _ _
Enter one letter: z
Wrong. 5 guesses left.
p _ _ _ _ _
Enter one letter: y
Correct: p y _ _ _ _

The exact word and output will vary because random.choice() selects a word at runtime.

Common Improvements

  • Add more words to WORDS or load them from a text file.
  • Print an ASCII drawing after each wrong guess.
  • Track wins and losses across multiple rounds.
  • Use categories such as easy, medium, and hard words.

After this project, another small game to practice the same ideas is Rock Paper Scissors in Python. You can also strengthen the iteration concepts with Python list iteration.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted