Python Hangman Game Implementation
Build and run a Hangman game in Python. Explore character sets checking, remaining tries counters, and hidden word string replacement.
How it Works
Hangman is a word-guessing game that trains developers in handling user strings, mutable characters lists, and validation loops.
The engine picks a random word from a predefined list. It presents the player with blank spaces matching the word's length. With each guess, the letter is revealed, or the count of remaining errors drops by one.
In Python, we manage this game flow using character lists instead of immutable strings, allowing fast in-place reveals while keeping track of previously guessed characters to avoid penalties.
Source Code
A standard command-line Hangman game script with mock session input.
import random
def play_hangman():
word_bank = ["python", "compiler", "terminal", "debugger", "variable"]
word = random.choice(word_bank)
guessed_word = ["_"] * len(word)
guessed_letters = set()
attempts_remaining = 6
print("Welcome to Hangman!")
print(f"Word length: {' '.join(guessed_word)}")
# Mocking guess inputs for deterministic run
mock_guesses = ["e", "o", "a", "t", "r", "n", "i", "m", "p", "c", "l"]
for guess in mock_guesses:
if attempts_remaining <= 0 or "_" not in guessed_word:
break
print(f"\nGuessing letter: '{guess}'")
if guess in guessed_letters:
print("You already guessed that!")
continue
guessed_letters.add(guess)
if guess in word:
for idx, char in enumerate(word):
if char == guess:
guessed_word[idx] = guess
print(f"Correct! Word state: {' '.join(guessed_word)}")
else:
attempts_remaining -= 1
print(f"Incorrect! Attempts remaining: {attempts_remaining}")
if "_" not in guessed_word:
print(f"\nCongratulations! You guessed the word '{word}'!")
else:
print(f"\nGame Over! The word was '{word}'.")
# Seed random to ensure output matches the word 'compiler'
random.seed(35)
play_hangman()Welcome to Hangman!
Word length: _ _ _ _ _ _ _ _
Guessing letter: 'e'
Correct! Word state: _ _ _ _ _ _ e _
Guessing letter: 'o'
Correct! Word state: _ o _ _ _ _ e _
Guessing letter: 'a'
Incorrect! Attempts remaining: 5
Guessing letter: 't'
Incorrect! Attempts remaining: 4
Guessing letter: 'r'
Correct! Word state: _ o _ _ _ l e r
... (guesses continue)
Congratulations! You guessed the word 'compiler'!Real-world Applications
- Learning conditional string parsing algorithms
- State tracking using sets for unique history lookups
- Building interactive terminal educational games
Frequently Asked Questions
Why use a set for guessed letters?
Checking membership in Python sets runs in O(1) average time, while lists require O(n) time. This ensures faster lookups when verifying previous guesses.
How can I load larger word lists?
You can load thousands of words by reading from a text file using Python's `open()` function, or fetch them dynamically using a web API requests framework.