thecodex.expert · The Codex Family of Knowledge
Tier 1 · Beginner · Python Project

Hangman

Guess the hidden word one letter at a time before you run out of lives. Learn tracking state across a game.

🧠 Teaches how to think spoonfed, every age Last verified:

1 The Problem

We want the classic hangman game: the computer picks a word, shows it as blanks, and the player guesses letters — revealing correct ones and losing a life for wrong ones, until they win or run out. It teaches tracking several pieces of game state at once: the word, the guesses, and the lives.

Where this shows up: any game or process with state that changes over time — a shopping cart, a multi-step form, a quiz in progress, a wizard. Keeping several related values in sync is a fundamental skill.

2 How to Think About It

Think about what the program must remember, before any code:

The plan — in plain English
1. Pick a secret word. → 2. Track three things: the letters guessed so far, the lives left, and the word shown as blanks-and-letters. → 3. Each turn: ask for a letter; if it is in the word, reveal it; if not, lose a life. → 4. Win when no blanks remain, lose when lives hit zero.

Yes

No

Yes

No

Yes

No

Pick a word

Show as blanks

Ask for a letter

In the word?

Reveal it

Lose a life

All revealed?

Lives left?

Win!

Game over

3 The Build — explained part by part

Here is the complete game. Each part is explained below.

Pythonhangman.py
import random

words = ["python", "coding", "codex", "program"]
word = random.choice(words)

guessed = set()       # letters the player has tried
lives = 6

while lives > 0:
    # Build the display: revealed letters, blanks for the rest.
    display = "".join(letter if letter in guessed else "_" for letter in word)
    print(display)

    if "_" not in display:
        print("You win!")
        break

    guess = input("Guess a letter: ").lower()
    if guess in guessed:
        print("Already tried that.")
        continue
    guessed.add(guess)

    if guess not in word:
        lives -= 1
        print(f"Nope. Lives left: {lives}")
else:
    print(f"Out of lives! The word was {word}.")
What each part does — in plain words
guessed = set() — a set holds the letters tried so far. A set automatically ignores duplicates, which is perfect here.

lives = 6 — the second piece of state: how many wrong guesses are left.

display = "".join(letter if letter in guessed else "_" ...) — build what the player sees: for each letter of the word, show it if guessed, otherwise show an underscore. This rebuilds every turn from the current state.

if "_" not in display: — if there are no blanks left, every letter is revealed, so the player has won.

guessed.add(guess) — record the guess. if guess not in word: lives -= 1 — a wrong guess costs a life.

while ... else: — the else on a loop runs only if the loop finished without break — here, that means lives ran out. A neat Python feature.
Common mistakes — and how to avoid them
✗ Using a list instead of a set for guesses — then duplicate guesses are not caught.
✓ A set ignores duplicates automatically.
✗ Rebuilding the display only once — it must rebuild every turn to show new reveals.
✓ Build display at the top of each loop from current state.
✗ Forgetting to lowercase the guess — “P” will not match “p”.
✓ Use .lower() on the guess.

4 Test & Prove Each Part

We test the display-building logic — the trickiest part — with known words and guesses.

With no guesses, the word shows as all blanks
A correct guess reveals that letter
Guessing every letter reveals the whole word
Pythontest_hangman.py
def make_display(word, guessed):
    """Show guessed letters, underscores for the rest."""
    return "".join(c if c in guessed else "_" for c in word)


def test_all_blanks():
    """No guesses means all underscores."""
    assert make_display("cat", set()) == "___"


def test_reveals_letter():
    """Guessing 'a' reveals it in 'cat'."""
    assert make_display("cat", {"a"}) == "_a_"


def test_full_reveal():
    """Guessing every letter shows the word."""
    assert make_display("cat", {"c", "a", "t"}) == "cat"

Run with pytest -v. The make_display function is the core logic, isolated so we can test it without playing a whole game. Isolating the tricky part is a smart testing move.

5 The Interface

INPUTa letterone letter per turn
What it expects
Guess a letter: p
OUTPUTword state + livesrevealed letters, lives left
What it returns
p_____
Guess a letter: y
py____

6 Run It & Automate It

Run it locally
python3 hangman.py
Guess one letter at a time before your 6 lives run out.

Jenkins runs the tests automatically — each line explained below.

What you should see when it works
Terminala real run
______
Guess a letter: p
p_____
Guess a letter: z
Nope. Lives left: 5
p_____
If it breaks — how to fix it
🚨 Correct letters are not revealed.
Check the display rebuilds each turn and the guess is lowercased to match the word.
🚨 The game never ends on a win.
Make sure you check if "_" not in display after rebuilding it.
GroovyJenkinsfile
// Jenkinsfile — automated tests on every change.
pipeline {
    agent any
    stages {
        stage('Get the code') { steps { checkout scm } }       // download the code
        stage('Install') { steps { sh 'python3 -m venv venv && . venv/bin/activate && pip install pytest' } }  // test tool
        stage('Test') { steps { sh '. venv/bin/activate && pytest -v' } }   // run every test
    }
    post {
        success { echo 'All tests passed.' }
        failure { echo 'A test failed — look above.' }
    }
}
🎯 Try this next — make it yours
  1. Draw the hangman. Show ASCII art for each life lost. (Teaches: mapping state to output.)
  2. Categories. Let the player pick a word theme. (Teaches: organising data.)
  3. Two players. Let one person enter the word for another. (Teaches: hiding input.)
What you learned
You learned to track several pieces of state at once (guessed letters, lives, display), use a set to avoid duplicates, and rebuild what the player sees from the current state each turn. Managing state is the heart of every interactive program. Related: random, Control Flow.