Build a Hangman Game in Python
Build a complete Hangman word-guessing game in Python step by step: pick a secret word, track guessed letters, limit wrong tries and detect a win or loss.
Key takeaways
- Hangman combines strings, loops, conditionals and sets into one real project
- A set is perfect for remembering which letters have already been guessed
- Build the masked word with a loop that shows guessed letters and underscores
- Track remaining lives and end the game on a full reveal or zero lives
What we are building
Hangman is a word-guessing game. The computer picks a secret word and shows it as a row of blanks. The player guesses one letter at a time. Correct letters get revealed; wrong letters cost a life. Guess the whole word before the lives run out and you win.
This is a fantastic project because it stitches together everything from earlier lessons: strings, loops, conditionals and sets. We will build it in clear stages and finish with the complete program.
Make sure you are comfortable with Python while loops and conditionals in Python first, since the game leans heavily on both.
Step 1: pick a secret word
import random
words = ["python", "guitar", "planet", "puzzle", "rocket"]
secret = random.choice(words)
import randomgives us tools for randomness.random.choice(words)picks one word from the list at random, so each game is different. You met this function in random numbers and games in Python.
Step 2: set up the game state
We need to remember which letters have been guessed and how many lives remain.
guessed = set() # letters the player has tried
lives = 6 # number of wrong guesses allowed
We use a set for guessed because a set automatically ignores duplicates. If the player types "a" twice, it is only stored once. Sets are covered in Python tuples and sets.
Step 3: show the masked word
We need a way to display the word with guessed letters revealed and the rest hidden.
def display(secret, guessed):
shown = ""
for letter in secret:
if letter in guessed:
shown += letter
else:
shown += "_"
return shown
print(display("python", {"p", "t"})) # p_t__n
Line by line:
- We loop over each
letterin the secret word. - If that letter is in the
guessedset, we add the real letter toshown. - Otherwise we add an underscore.
- The function returns the finished masked string.
This single helper function will be called every turn to redraw the word.
Step 4: the main game loop
Now we put it together. The loop keeps running until the player wins or runs out of lives.
import random
words = ["python", "guitar", "planet", "puzzle", "rocket"]
secret = random.choice(words)
guessed = set()
lives = 6
def display(secret, guessed):
shown = ""
for letter in secret:
shown += letter if letter in guessed else "_"
return shown
print("Welcome to Hangman!")
while lives > 0:
print("\nWord:", display(secret, guessed))
print("Lives left:", lives)
guess = input("Guess a letter: ").lower()
if len(guess) != 1 or not guess.isalpha():
print("Please type a single letter.")
continue
if guess in guessed:
print("You already tried that letter.")
continue
guessed.add(guess)
if guess in secret:
print("Good guess!")
else:
lives -= 1
print("Nope, that letter is not in the word.")
# Have we revealed the whole word?
if all(letter in guessed for letter in secret):
print("\nYou win! The word was:", secret)
break
else:
print("\nOut of lives! The word was:", secret)
Let's unpack the important parts:
while lives > 0:keeps playing while at least one life remains.input("Guess a letter: ").lower()reads the guess and converts it to lowercase so "A" and "a" match.if len(guess) != 1 or not guess.isalpha():rejects empty input, multiple letters, or non-letters.continueskips back to the top of the loop without using a life.if guess in guessed:stops the same letter from wasting a turn.guessed.add(guess)records the new letter in the set.- If the guess is in the secret word, we praise the player; otherwise
lives -= 1removes a life. all(letter in guessed for letter in secret)isTrueonly when every letter of the word has been guessed — that is the win condition.breakthen ends the loop.- The
elseattached to thewhileruns only if the loop finished withoutbreak, meaning lives hit zero — a loss. This is the Python while-else pattern in action.
Worked example: one playthrough
Suppose the secret word is rocket and you guess r, o, x, c, k, e, t.
Word: ______ guess r -> Good guess! -> r_____
Word: r_____ guess o -> Good guess! -> ro____
Word: ro____ guess x -> Nope -> lives 5
Word: ro____ guess c -> Good guess! -> roc___ ... wait
Actually c appears at position three, so the board becomes roc__t once t is also found. Each correct guess fills in every matching position because display checks the whole word. After guessing all six distinct letters, all(...) becomes True and you win with lives to spare.
Common mistakes
- Using a list instead of a set for guesses. A list lets duplicates pile up; a set keeps each letter once.
- Forgetting
.lower(). Without it, uppercase guesses never match a lowercase secret word. - Decrementing lives on every guess. Only wrong guesses should cost a life. The
if guess in secretcheck guards against this. - Checking the win condition incorrectly.
all(letter in guessed for letter in secret)is the reliable way; counting underscores by hand is error-prone.
Try it yourself
- Add a list of already-guessed letters to the display so the player can see their history.
- Give the player a hint by revealing one random letter at the start.
- Read the word list from a text file so you can add hundreds of words, building on reading and writing files in Python.
For another project that mixes randomness and loops, try the number guessing game in Python.
Quick quiz
Test yourself and earn XP
Why use a set to store guessed letters?
A set automatically ignores duplicates, which is ideal for tracking unique guessed letters.
How do we show the word with hidden letters?
We loop through the secret word and reveal letters that were guessed, showing underscores for the rest.
When has the player won?
The player wins once all the letters in the secret word appear in the guessed set.
When does the player lose?
The player loses when wrong guesses reduce the remaining lives to zero.
Which loop type fits the main game best?
A while loop is ideal because we do not know in advance how many guesses the game will take.
FAQ
No. The core game uses only built-in Python. We use the random module to pick a secret word, and random is part of the standard library.
Just add more strings to the words list. For a bigger game you could read words from a text file, which connects nicely to file-handling skills.
Players might type uppercase letters. Converting both the secret word and the guess to lowercase makes comparisons consistent so 'A' and 'a' are treated as the same letter.
Keep exploring
More in Coding