Hangman Game Code in Python (Full Program)

4 days ago 18
Club.noww.in

Hangman game code in Python comes down to four pieces: pick a secret word with random.choice(), show it as underscores, keep guessed letters in a set, and count misses until the drawing is complete. The masking line does most of the work:

" ".join(ch if ch in guessed else "_" for ch in word) # c _ _ c a _ _

I played the full game below in a real Command Prompt with Python 3.12.5, typing every guess, including a few mistakes on purpose.

We’ll build the masking function, the full game with ASCII gallows and input checks, and a tiny helper that suggests good first guesses.

Showing the hidden word

Every turn, letters you’ve guessed appear and the rest stay as underscores, so you can’t see the word. A set makes the membership check fast:

def masked(word, guessed): return " ".join(ch if ch in guessed else "_" for ch in word) print(masked("chicago", set())) print(masked("chicago", {"c", "a"})) print(masked("chicago", set("chicago")))

Output:

_ _ _ _ _ _ _ c _ _ c a _ _ c h i c a g o
Command Prompt output of a Python hangman masking function showing a hidden city name with no guesses, two guesses and all lettersThe same word with no guesses, two correct letters, and every letter guessed.

Using a set for guessed also makes “have I tried this already?” a one-line check. See list vs set in Python for why sets suit this.

Hangman game code in Python (full program)

The game picks a US city, and it loops until you’ve run out of misses, and draws one more piece of the figure each time you guess wrong:

import random WORDS = ["denver", "boston", "phoenix", "seattle", "atlanta", "chicago", "houston", "orlando"] 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 play(): random.seed(11) # fixed seed for this demo; remove it for a new word each time word = random.choice(WORDS) guessed, misses = set(), 0 print("Guess the US city!") while misses < len(STAGES) - 1: print(" ".join(ch if ch in guessed else "_" for ch in word)) guess = input("Letter: ").strip().lower() if len(guess) != 1 or not guess.isalpha(): print(" Type a single letter.") continue if guess in guessed: print(f" You already tried '{guess}'.") continue guessed.add(guess) if guess in word: print(" Yes!") if set(word) <= guessed: print(f"You win! The city was {word.title()} with {misses} miss(es).") return else: misses += 1 print(f" No '{guess}'. Misses: {misses}") print(STAGES[misses]) print(f"Out of guesses. The city was {word.title()}.") play()

Output:

Guess the US city! _ _ _ _ _ _ _ Letter: e No 'e'. Misses: 1 +---+ O | | | === _ _ _ _ _ _ _ Letter: a Yes! _ _ _ a _ _ _ Letter: x No 'x'. Misses: 2 +---+ O | | | | === _ _ _ a _ _ _ Letter: 1 Type a single letter. _ _ _ a _ _ _ Letter: a You already tried 'a'. _ _ _ a _ _ _ Letter: o Yes! o _ _ a _ _ o Letter: n Yes! o _ _ a n _ o Letter: r Yes! o r _ a n _ o Letter: t No 't'. Misses: 3 +---+ O | /| | | === o r _ a n _ o Letter: l Yes! o r l a n _ o Letter: d Yes! You win! The city was Orlando with 3 miss(es).
Command Prompt showing a Python hangman game with guesses, ASCII gallows drawings, invalid input messages and a winThree misses, one invalid input and one repeated letter, then the win. Repeats and non-letters don’t cost a miss.

The win check, set(word) <= guessed, asks whether every letter in the word has been guessed. The input checks use isalpha(), explained in what isalpha does in Python.

How do you pick a good first guess in hangman?

You can count how many words each letter appears in; it’s a quick trick. Letters that show up in the most words are the best openers:

from collections import Counter WORDS = ["denver", "boston", "phoenix", "seattle", "atlanta", "chicago", "houston", "orlando"] letters = Counter(ch for w in WORDS for ch in set(w)) # in how many words each letter appears print("best first guesses:", [ch for ch, _ in letters.most_common(5)])

Output:

best first guesses: ['n', 'o', 't', 'a', 'e']
Command Prompt output of a Python Counter finding the most common letters across the hangman word listFor this word list, vowels and a few common consonants lead the pack.

Counter.most_common() does the ranking. The same idea makes a decent computer player, like the minimax bot in tic tac toe.

Ideas to extend your hangman game

  • Load words from a text file so the list can be as long as you like.
  • Let the player guess the whole word for a bonus.
  • Add difficulty levels with longer words or fewer allowed misses.
  • Keep score across rounds in a dictionary.

For loading words, see reading a file into a list.

More Python games you can build:

Frequently asked questions

How do you make a hangman game in Python?

Pick a word with random.choice(), store guesses in a set, show the word with underscores for unknown letters, and loop until the word is found or the misses run out.

How do I show underscores for hidden letters?

Use " ".join(ch if ch in guessed else "_" for ch in word).

How do I stop repeated guesses counting as misses?

Check if guess in guessed before processing it, and continue to ask again.

How do I check if the player won?

Compare sets: set(word) <= guessed is True when every letter has been guessed.

How can I draw the hangman?

Store each stage as a multi-line string in a list and print STAGES[misses] after a wrong guess.

Where is random.choice documented?

See random.choice in the Python docs.

Read Entire Article