Skip to content
Python project #14Intermediate

Hangman

Guess letters or whole words across categories, with an ASCII gallows, repeated-guess detection, replays and a running score.

Estimated time
~3 hours to build
Files
4 files · 377 lines
Technologies
Python 3, random.Random, Sets

Introduction

Hangman combines string handling, sets and a game loop. This version draws the gallows stage by stage, accepts whole-word guesses, refuses repeated or invalid guesses without penalty and can be seeded for repeatable tests.

Problem statement

Pick a random category and word. Show the gallows, the masked word, wrong guesses and lives left. Accept single letters or a whole-word guess; a wrong letter or wrong word costs a life, while invalid input and repeated guesses don't. Six wrong guesses lose the game. After each game, offer another and keep the score.

Objectives

  • Use sets to track guessed letters
  • Build display strings with comprehensions and join
  • Write a game loop with several end conditions
  • Use seeded randomness for testing

Features

  • Three word categories
  • Seven-stage ASCII gallows
  • Letter and whole-word guesses
  • Repeated and invalid guesses don't cost lives
  • Replays with a win/loss score

Concepts demonstrated

  • Sets
  • String building
  • Game loops
  • Seeded randomness

System architecture

WORDS maps categories to word lists and STAGES holds the seven drawings. play chooses a word with the shared random.Random, then loops while lives remain: it validates the guess, updates the guessed set or the wrong list and checks for a win. masked builds the display with underscores. main reads the seed and runs games until the player stops.

Folder structure

TextProject tree
hangman-game/
├── README.md
├── main.py
├── tests/expected-output.txt
└── tests/sample-input.txt

Complete source code

main.py

102 lines
Pythonmain.py
"""Hangman: guess the hidden word letter by letter before the drawing is complete.
Type a seed at the start for a repeatable word (useful for testing) or press Enter.
You may guess a single letter or the whole word. A wrong whole-word guess costs one life.
"""
import random
import sys
WORDS = {
"animals": ["elephant", "giraffe", "penguin", "dolphin", "kangaroo", "tiger"],
"programming": ["python", "variable", "function", "iterator", "dictionary", "recursion"],
"india": ["mumbai", "himalaya", "monsoon", "chennai", "jaipur", "ganga"],
}
STAGES = [
[" +---+", " |", " |", " |", " ==="],
[" +---+", " O |", " |", " |", " ==="],
[" +---+", " O |", " | |", " |", " ==="],
[" +---+", " O |", " /| |", " |", " ==="],
[" +---+", " O |", " /|\\ |", " |", " ==="],
[" +---+", " O |", " /|\\ |", " / |", " ==="],
[" +---+", " O |", " /|\\ |", " / \\ |", " ==="],
]
LIVES = len(STAGES) - 1
def ask(prompt: str) -> str | None:
try:
line = input(prompt)
except EOFError:
print()
return None
if not sys.stdin.isatty():
print(line)
return line.strip().lower()
def masked(word: str, guessed: set[str]) -> str:
return " ".join(c if c in guessed else "_" for c in word)
def play(rng: random.Random) -> bool | None:
category = rng.choice(sorted(WORDS))
word = rng.choice(WORDS[category])
guessed: set[str] = set()
wrong: list[str] = []
print(f"Category: {category} ({len(word)} letters)")
while len(wrong) < LIVES:
print("\n".join(STAGES[len(wrong)]))
print(f"Word: {masked(word, guessed)} Wrong: {' '.join(wrong) or '-'} Lives: {LIVES - len(wrong)}")
guess = ask("Your guess: ")
if guess is None:
return None
if len(guess) > 1:
if not guess.isalpha():
print("Letters only, please.")
elif guess == word:
guessed.update(word)
break
else:
print(f"'{guess}' is not the word.")
wrong.append(guess)
continue
if not guess.isalpha() or len(guess) != 1:
print("Type a single letter (or the whole word).")
elif guess in guessed or guess in wrong:
print(f"You already tried '{guess}'.")
elif guess in word:
guessed.add(guess)
print(f"Yes! '{guess}' appears {word.count(guess)} time(s).")
if all(c in guessed for c in word):
break
else:
wrong.append(guess)
print(f"No '{guess}'.")
if all(c in guessed for c in word):
print(f"You won! The word was {word.upper()} with {LIVES - len(wrong)} li{'fe' if LIVES - len(wrong) == 1 else 'ves'} to spare.")
return True
print("\n".join(STAGES[-1]))
print(f"You lost. The word was {word.upper()}.")
return False
def main() -> None:
seed = ask("Seed (press Enter for random): ")
if seed is None:
return
rng = random.Random(int(seed)) if seed.isdigit() else random.Random()
wins = losses = 0
while True:
result = play(rng)
if result is None:
break
wins, losses = wins + result, losses + (not result)
again = ask("Play again? (y/n): ")
if again != "y":
break
print(f"Final score: {wins} won, {losses} lost.")
if __name__ == "__main__":
main()

What each file does

main.py
Word lists, gallows drawings, the game loop and the replay loop.

How to run it

Run

Terminal
python main.py # use python3 on Linux / macOS

Test against the expected output

Terminal
python main.py < tests/sample-input.txt > actual.txt
diff actual.txt tests/expected-output.txt
# Windows PowerShell:
# Get-Content tests\sample-input.txt | python main.py > actual.txt

Expected output

Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.

Texttests/expected-output.txt
Seed (press Enter for random): 3
Category: animals (8 letters)
+---+
|
|
|
===
Word: _ _ _ _ _ _ _ _ Wrong: - Lives: 6
Your guess: a
Yes! 'a' appears 2 time(s).
+---+
|
|
|
===
Word: _ a _ _ a _ _ _ Wrong: - Lives: 6
Your guess: e
No 'e'.
+---+
O |
|
|
===
Word: _ a _ _ a _ _ _ Wrong: e Lives: 5
Your guess: k
Yes! 'k' appears 1 time(s).
+---+
O |
|
|
===
Word: k a _ _ a _ _ _ Wrong: e Lives: 5
Your guess: 1
Type a single letter (or the whole word).
+---+
O |
|
|
===
Word: k a _ _ a _ _ _ Wrong: e Lives: 5
Your guess: zebra
'zebra' is not the word.
+---+
O |
| |
|
===
Word: k a _ _ a _ _ _ Wrong: e zebra Lives: 4
Your guess: a
You already tried 'a'.
+---+
O |
| |
|
===
Word: k a _ _ a _ _ _ Wrong: e zebra Lives: 4
Your guess: n
Yes! 'n' appears 1 time(s).
+---+
O |
| |
|
===
Word: k a n _ a _ _ _ Wrong: e zebra Lives: 4
Your guess: g
Yes! 'g' appears 1 time(s).
+---+
O |
| |
|
===
Word: k a n g a _ _ _ Wrong: e zebra Lives: 4
Your guess: r
Yes! 'r' appears 1 time(s).
+---+
O |
| |
|
===
Word: k a n g a r _ _ Wrong: e zebra Lives: 4
Your guess: o
Yes! 'o' appears 2 time(s).
You won! The word was KANGAROO with 4 lives to spare.
Play again? (y/n): y
Category: programming (8 letters)
+---+
|
|
|
===
Word: _ _ _ _ _ _ _ _ Wrong: - Lives: 6
Your guess: x
No 'x'.
+---+
O |
|
|
===
Word: _ _ _ _ _ _ _ _ Wrong: x Lives: 5
Your guess: q
No 'q'.
+---+
O |
| |
|
===
Word: _ _ _ _ _ _ _ _ Wrong: x q Lives: 4
Your guess: x
You already tried 'x'.
+---+
O |
| |
|
===
Word: _ _ _ _ _ _ _ _ Wrong: x q Lives: 4
Your guess: z
No 'z'.
+---+
O |
/| |
|
===
Word: _ _ _ _ _ _ _ _ Wrong: x q z Lives: 3
Your guess: w
No 'w'.
+---+
O |
/|\ |
|
===
Word: _ _ _ _ _ _ _ _ Wrong: x q z w Lives: 2
Your guess: j
No 'j'.
+---+
O |
/|\ |
/ |
===
Word: _ _ _ _ _ _ _ _ Wrong: x q z w j Lives: 1
Your guess: k
No 'k'.
+---+
O |
/|\ |
/ \ |
===
You lost. The word was VARIABLE.
Play again? (y/n): n
Final score: 1 won, 1 lost.
Input
3
a
e
k
1
zebra
a
n
g
r
o
y
x
q
x
z
w
j
k
n

Testing

  • Run python main.py < tests/sample-input.txt and compare with tests/expected-output.txt.
  • Seed 3 chooses KANGAROO and then VARIABLE.
  • In game 1, '1' is rejected, 'zebra' costs a life and the repeated 'a' is free; the word is solved with 4 lives left.
  • In game 2, six wrong letters complete the gallows and the game is lost.

Common errors

Guessing the same letter twice costs a life

Check the guessed set and the wrong list before applying a penalty.

A whole-word guess with digits is accepted

Check guess.isalpha() before comparing with the word.

Possible improvements

  • Load words from a text file
  • Add difficulty levels by word length
  • Show a hint after three wrong guesses

Additional challenges

  1. 1Add a two-player mode where one player enters the word secretly.
  2. 2Track statistics per category across games.
  3. 3Write an AI that guesses letters by frequency.

Built and tested it yourself? Mark it to update your dashboard.