Python project 11
Python Hangman Game Project
Build a command-line Hangman game that chooses a secret word, validates each guess, tracks missed letters, and lets the player start another round. The project turns strings, sets, loops, and functions into a complete playable program.
Learn Python with mentor-guided projectsView all project ideas
What you will build
The program selects a word with Python’s security-focused random generator, hides unguessed letters, rejects repeated or invalid input, and ends cleanly after a win or six wrong guesses.
Skills practised
- Strings and character checks
- Sets and membership tests
- Loops and reusable functions
- Random selection with secrets
Requirements
- Python 3.10 or later
- A terminal or command prompt
- No external packages
- About 35 minutes to build
Full Python code
Save this code as hangman_game.py, then follow the run instructions below.
"""A small, dependency-free command-line Hangman game."""
from __future__ import annotations
import secrets
import string
WORDS = (
"algorithm",
"function",
"iterator",
"variable",
"terminal",
"database",
"python",
"software",
)
MAX_WRONG_GUESSES = 6
def masked_word(word: str, guessed: set[str]) -> str:
"""Return a spaced display that reveals only guessed letters."""
return " ".join(letter if letter in guessed else "_" for letter in word)
def read_guess(guessed: set[str]) -> str:
"""Read one new English letter from the player."""
while True:
guess = input("Guess one letter: ").strip().lower()
if len(guess) != 1 or guess not in string.ascii_lowercase:
print("Enter exactly one letter from A to Z.")
elif guess in guessed:
print("You already tried that letter.")
else:
return guess
def play(word: str | None = None) -> bool:
"""Play one game and return True when the player wins."""
secret_word = (word or secrets.choice(WORDS)).lower()
if not secret_word.isascii() or not secret_word.isalpha():
raise ValueError("The secret word must contain only A-Z letters.")
guessed: set[str] = set()
wrong_guesses = 0
print("\nPython Hangman")
print(f"The word has {len(secret_word)} letters.")
while wrong_guesses < MAX_WRONG_GUESSES:
print(f"\nWord: {masked_word(secret_word, guessed)}")
print(f"Wrong guesses remaining: {MAX_WRONG_GUESSES - wrong_guesses}")
if guessed:
print("Tried:", " ".join(sorted(guessed)))
guess = read_guess(guessed)
guessed.add(guess)
if guess not in secret_word:
wrong_guesses += 1
print("That letter is not in the word.")
if set(secret_word) <= guessed:
print(f"\nYou won! The word was {secret_word}.")
return True
print(f"\nGame over. The word was {secret_word}.")
return False
def main() -> None:
while True:
play()
again = input("Play again? [y/N]: ").strip().lower()
if again != "y":
print("Thanks for playing.")
break
if __name__ == "__main__":
main()
How the project works
masked_word() builds the display from the secret word and the set of letters already tried. Sets are useful here because membership checks are fast and each letter is stored only once.
read_guess() accepts exactly one English letter and does not charge the player for invalid or repeated input. The game loop counts only wrong guesses and compares the set of unique secret-word letters with the guessed set to detect a win.
Run the project
- Save the code as
hangman_game.py. - Run
python hangman_game.py. - Enter one letter at a time.
- Choose
yafter a round if you want to play again.
Accuracy and safety notes
- Fair randomness:
secrets.choice()avoids predictable selection. - Repeated letters: one correct guess reveals every matching position.
- Validation: invalid input does not reduce the remaining guesses.
Ways to extend it
Add difficulty levels, word categories, a saved high score, a graphical interface, or a two-player mode in which one player supplies the secret word.
Continue learning Python
Build the next project, return to the Softenant project library, or explore the Python programming course in Vizag for structured lessons, mentor feedback, and portfolio practice.