Hangman in Python (1/6): brief and masked word
Set hangman rules, hardcode a secret word, build a mask of underscores the same length, and reveal each letter when the player guesses it right.
Getting started
Home Assistant
Buying
Set hangman rules, hardcode a secret word, build a mask of underscores the same length, and reveal each letter when the player guesses it right.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
Hangman is a letter game: the computer picks a secret word; the player suggests letters. Each correct letter reveals its positions; each wrong letter costs a life. At zero lives, or when the word is fully revealed, the game stops.
This series has six articles. This one sets the rules and the core with no file: a fixed word in the code.
Hangman series (1/6) — Contents · next: Part 2 — words from a file
You work in a terminal (PowerShell, Command Prompt, or the built-in terminal in VS Code / Thonny): you run each script with python your_file.py.
Example after a letter is found:

A teaching screenshot of the terminal output for this tutorial (run locally).
A simple trick: build a list or a string of the same length as the word, with _ or - for unknown letters.
mot = "ROBOT"
masque = ["_"] * len(mot) # ['_', '_', '_', '_', '_']
When the player guesses O:
for i, lettre in enumerate(mot):
if lettre == "O":
masque[i] = "O"
print(" ".join(masque)) # _ O _ O _
A set is a perfect fit: membership tests are O(1) on average.
essayees = set()
c = input("A letter: ").strip().upper()
if len(c) != 1 or not c.isalpha():
print("One letter only.")
elif c in essayees:
print("Already guessed.")
else:
essayees.add(c)
'_' not in masque) or a loss (vies == 0).mot = "CODE", walk through two turns by hand: C, then X.mot_termine(masque) that returns True when there is no _ left."BATAILLE" contains (expected result: 6).Part 2 — Load a word list from a text file. A sample file is on the site: /examples/mots-pendu.txt (copy it next to your script locally).
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Hangman — Chapter 1/6: masked word, one letter, update (no infinite loop).
Run: python pendu_chapitre_01.py
"""
VIES_INIT = 7
def main():
mot = "ROBOT"
masque = ["_"] * len(mot)
essayees = set()
vies = VIES_INIT
print("Word:", " ".join(masque), "| Lives:", vies)
c = input("A letter: ").strip().upper()
if len(c) != 1 or not c.isalpha():
print("Enter a single letter A-Z.")
return
if c in essayees:
print("Already guessed.")
return
essayees.add(c)
trouve = False
for i, lettre in enumerate(mot):
if lettre == c:
masque[i] = c
trouve = True
if not trouve:
vies -= 1
print("After this guess:", " ".join(masque), "| Lives:", vies)
print("Guessed:", " ".join(sorted(essayees)))
if "_" not in masque:
print("Well done, you found the word!")
elif vies <= 0:
print("You lose! The word was:", mot)
if __name__ == "__main__":
main()
A book search for Python projects and games: Check today’s price on Amazon.
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).