Nested Loops Mini Project — Hangman
The problem...
One player knows the word. The other doesn't.
Letter by letter — the word gets revealed. Or the player runs out of chances.
The idea!
Player 1 enters the word. The screen clears with empty lines. Player 2 guesses one letter at a time. while keeps the game running. for checks each guess against every letter in the word.
The setup
word = input("Player 1 — enter a word: ").lower()
print("\n" * 50) # clear the screen
50 empty lines push the word off screen. Not perfect — but good enough for two players sitting together.
The solution
word = input("Player 1 — enter a word: ").lower()
print("\n" * 50)
guessed = ""
max_attempts = 6
# longer words need more chances
wrong = 0
while wrong < max_attempts:
display = ""
for letter in word:
if letter in guessed:
display += letter + " "
else:
display += "_ "
print(f"Word: {display}")
print(f"Wrong attempts: {wrong}/{max_attempts}")
print(f"Guessed: {guessed}")
if "_" not in display:
print("Player 2 wins!")
break
guess = input("Guess a letter: ").lower()
if guess in guessed:
print("Already guessed.")
continue
guessed += guess
found = False
for letter in word:
if letter == guess:
found = True
break
if not found:
wrong += 1
print(f"Wrong! {max_attempts - wrong} attempts left.")
else:
print(f"Player 2 loses. The word was '{word}'.")
Test it
# Player 1 — enter a word: python
# Word: _ _ _ _ _ _
# Wrong attempts: 0/6
# Guessed:
# Guess a letter: p
# Word: p _ _ _ _ _
# Wrong attempts: 0/6
# Guessed: p
# Guess a letter: x
# Wrong! 5 attempts left.
What's really happening
while keeps the game alive — as long as wrong attempts are under the limit. The first for builds the display — checking each letter against what's been guessed. The second for checks if the new guess is in the word. continue skips duplicate guesses. while...else handles the loss — it runs only if the loop exhausted all attempts without a break.
Go further
- Add a drawing — print a simple ASCII hangman that grows with each wrong guess
- Allow guessing the full word — not just one letter
- Add a round counter — best of 3
What you should understand now
whilecontrols the game —forprocesses letters inside each turn- Two
forloops — one builds the display, one checks the guess continueskips duplicate guesses cleanlywhile...elsehandles the loss — runs only when the loop wasn't interrupted bybreak