Hangman is the word game every Python course builds, because it is all about strings: hiding letters, revealing them, and checking guesses. This version draws the gallows in ASCII art, remembers the letters you have tried and gives you six wrong guesses.
Guess letters in the console below, then learn how each part works.
Play Hangman
Press βΆ Play to start the game. When it asks you something, type your answer and press Enter.
View and edit the code (52 lines)
How to play
- The word is shown as dashes, one per letter.
- Guess one letter at a time. Right letters appear in place.
- Six wrong letters and the drawing is finished: you lose. Reveal the whole word to win.
The complete Hangman code
Here is the whole program (52 lines). It only uses Python's standard library, so it runs anywhere Python 3 is installed.
import random
WORDS = ["python", "keyboard", "variable", "function", "rocket", "puzzle",
"planet", "laptop", "garden", "pirate", "jungle", "tomato"]
STAGES = [
" +---+\n |\n |\n |\n ===",
" +---+\n O |\n |\n |\n ===",
" +---+\n O |\n | |\n |\n ===",
" +---+\n O |\n /| |\n |\n ===",
" +---+\n O |\n /|\\ |\n |\n ===",
" +---+\n O |\n /|\\ |\n / |\n ===",
" +---+\n O |\n /|\\ |\n / \\ |\n ===",
]
def masked(word, guessed):
return " ".join(ch if ch in guessed else "_" for ch in word)
word = random.choice(WORDS)
guessed = set()
wrong = 0
print("HANGMAN - guess the word one letter at a time")
while wrong < 6:
print()
print(STAGES[wrong])
print("Word:", masked(word, guessed))
if guessed:
print("Tried:", " ".join(sorted(guessed)))
if all(ch in guessed for ch in word):
break
letter = input("Guess a letter: ").strip().lower()
if len(letter) != 1 or not letter.isalpha():
print("Type a single letter.")
elif letter in guessed:
print("You already tried", letter)
else:
guessed.add(letter)
if letter in word:
print("Yes!", letter, "is in the word.")
else:
wrong += 1
print("No", letter, "-", 6 - wrong, "wrong guesses left.")
if wrong < 6:
print(f"\nYou got it: {word.upper()}!")
else:
print()
print(STAGES[6])
print(f"Out of guesses. The word was {word.upper()}.")How the Hangman game works, step by step
01Pick a secret word
random.choice(WORDS) pulls one word from the list. Add your own words; they just need to be lowercase letters.
word = random.choice(WORDS)02Hide the letters you haven't guessed
A generator expression walks through the word and shows each letter only if it is in the guessed set, otherwise an underscore. " ".join() spaces them out.
def masked(word, guessed):
return " ".join(ch if ch in guessed else "_" for ch in word)03Remember guesses in a set
A set stores each letter once and answers letter in guessed instantly. sorted(guessed) lists them alphabetically for the player.
guessed = set()
guessed.add(letter)04Draw the gallows from a list
Seven ASCII pictures sit in a list. The number of wrong guesses is the index of the picture to print, so drawing the game takes one line: print(STAGES[wrong]).
print(STAGES[wrong])05Know when the game ends
The loop runs while there are fewer than six wrong guesses. all(ch in guessed for ch in word) becomes True when every letter has been found, and break leaves the loop with a win.
if all(ch in guessed for ch in word):
breakWhat you'll learn
- String methods:
.lower(),.isalpha(),.join() - Sets for fast membership tests
- Generator expressions with
all() - Lists of multi-line strings for ASCII art
- Validating input before using it
Python concepts in this game:
Hangman coding challenges
Write the key parts of the game yourself. Press Run to try your code and Check to test it. Each challenge you pass earns a star (saved in this browser).
Hide the word
Write masked(word, guessed): return the word with every letter not in guessed replaced by _, and letters separated by single spaces. masked("tomato", {"t", "o"}) is "t o _ _ t o".
Hint
Build a list of characters (the letter or "_"), then " ".join(the_list).
Show a solution
def masked(word, guessed):
shown = []
for ch in word:
if ch in guessed:
shown.append(ch)
else:
shown.append("_")
return " ".join(shown)
print(masked("tomato", {"t", "o"}))Has the player won?
Write solved(word, guessed) that returns True only when every letter of word is in guessed.
Hint
Loop over the word and return False as soon as one letter is missing. If the loop finishes, return True.
Show a solution
def solved(word, guessed):
for ch in word:
if ch not in guessed:
return False
return True
print(solved("pirate", set("pirate")))Check a guess
Write check(letter, guessed). Return "bad" if letter isn't exactly one alphabet letter, "again" if it is already in guessed, otherwise add it to the set and return "ok".
Hint
Test the bad cases first with len(letter) != 1 or not letter.isalpha().
Show a solution
def check(letter, guessed):
if len(letter) != 1 or not letter.isalpha():
return "bad"
if letter in guessed:
return "again"
guessed.add(letter)
return "ok"
tried = {"a"}
print(check("b", tried), tried)Make it your own
Once your challenges pass, try one of these upgrades:
- Add categories (animals, food, space) and let the player choose.
- Give a hint that reveals one letter but costs a guess.
- Load hundreds of words from a text file.
- Make a two-player mode where one person types the secret word.
Frequently asked questions
How do you make Hangman in Python?
Pick a random word, keep the guessed letters in a set, show the word with underscores for hidden letters, and loop until the word is revealed or six wrong guesses are used up.
How do I draw the hangman picture in Python?
Store each stage as a multi-line string in a list and print the item whose index equals the number of wrong guesses.
Can I add my own words?
Yes. Edit the WORDS list at the top of the code. Use lowercase letters only, because the player's guesses are turned into lowercase.