Hangman in Python (4/6): game loop and input checks
Use a while True game loop with clear win and loss exits, reject a bad or repeated letter, and play again without restarting the Python script.
Getting started
Home Assistant
Buying
Use a while True game loop with clear win and loss exits, reject a bad or repeated letter, and play again without restarting the Python script.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
Direct answer (November 2026) — Wrap each game in a
while Trueloop andbreakon a win or a loss, and keepdemander_lettre_valide()running until you get one alphabetic letter that has never been guessed.
You have the building blocks (mask, file, display). You need a clean loop that chains turns until a win or a loss, without letting the program crash on a clumsy guess. This chapter sits in the hangman project in Python (the hub for the six-part path). Next: part 5 — winning and losing.

while True structure with breakwhile True:
afficher_etat(masque, vies, essayees)
if "_" not in masque:
print("You win!")
break
if vies <= 0:
print("You lose! The word was:", secret)
break
lettre = demander_lettre_valide(essayees)
# ... update masque / vies / essayees
demander_lettre_valide loops internally until it gets a new single letter.
demander_lettre_valide functiondef demander_lettre_valide(essayees):
while True:
c = input("Letter? ").strip().upper()
if len(c) != 1 or not c.isalpha():
print("One letter only, A-Z.")
continue
if c in essayees:
print("Already guessed.")
continue
return c
After break, ask Play again? (y/n). If the answer is yes, load a new word, reset the mask, lives and essayees, and start a new loop (or put the whole game in a function jouer_une_partie() called from an outer loop).
vies_initiales parameter passed to jouer_une_partie.Why while True rather than a for?
The number of turns depends on the letters found: you break as soon as the mask has no _ left or lives drop to zero.
How do you avoid a crash on an empty guess?
Keep validation inside demander_lettre_valide(): an inner loop until you get a single A–Z letter.
Where does the “play again” loop go?
Either an outer loop around jouer_une_partie(), or a menu in main() — see the full script below.
Part 5 — End messages, revealing the word, a complete hangman.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Hangman — Chapter 4/6: full loop plus play again.
Run: python pendu_chapitre_04.py
"""
import random
from pathlib import Path
BASE = Path(__file__).resolve().parent
CHEMIN_MOTS = BASE / "mots_pendu.txt"
PENDU_ETAPES = [
"",
" O ",
" O\n | ",
" O\n/| ",
" O\n/|\\\n",
" O\n/|\\\n/",
" O\n/|\\\n/ \\",
]
VIES_MAX = 7
def charger_mots(chemin):
with open(chemin, "r", encoding="utf-8") as f:
lignes = f.read().splitlines()
mots = [L.strip().upper() for L in lignes if L.strip()]
mots = [m for m in mots if len(m) >= 3]
if not mots:
raise ValueError("No words in the file.")
return mots
def afficher_etat(masque, vies, essayees):
erreurs = VIES_MAX - vies
etape = min(erreurs, len(PENDU_ETAPES) - 1)
if PENDU_ETAPES[etape]:
print(PENDU_ETAPES[etape])
print("\n" + " ".join(masque))
print(f"Lives: {vies}")
print("Letters guessed:", " ".join(sorted(essayees)))
def demander_lettre_valide(essayees):
while True:
c = input("Letter? ").strip().upper()
if len(c) != 1 or not c.isalpha():
print("One letter only, A-Z.")
continue
if c in essayees:
print("Already guessed.")
continue
return c
def jouer_une_partie(secret):
masque = ["_"] * len(secret)
essayees = set()
vies = VIES_MAX
while True:
afficher_etat(masque, vies, essayees)
if "_" not in masque:
print("You win!")
return True
if vies <= 0:
print("You lose! The word was:", secret)
return False
lettre = demander_lettre_valide(essayees)
essayees.add(lettre)
if lettre not in secret:
vies -= 1
else:
for i, L in enumerate(secret):
if L == lettre:
masque[i] = lettre
def main():
try:
mots = charger_mots(CHEMIN_MOTS)
except FileNotFoundError:
print("Put mots_pendu.txt next to the script.")
return
while True:
secret = random.choice(mots)
jouer_une_partie(secret)
if input("\nPlay again? (y/n) ").strip().lower() not in ("o", "oui", "y", "yes"):
break
if __name__ == "__main__":
main()
pendu_chapitre_04.py — with mots_pendu.txt.
A book search for Python algorithms for beginners: 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).