🐍
Build Hangman Game 🎯
Intermediate
160 XP
70 min
Lesson Content
Build Hangman Game 🎯
Create a classic Hangman game in Python! This teaches you string manipulation, loops, and game logic.
Game Logic
import random
words = ['python', 'javascript', 'coding', 'developer']
word = random.choice(words)
guessed = []
attempts = 6
while attempts > 0:
display = ''.join([letter if letter in guessed else '_' for letter in word])
print(display)
guess = input('Guess a letter: ')
guessed.append(guess)
if guess not in word:
attempts -= 1Example Code
Build the core hangman game logic
import random
words = ['python', 'code', 'game']
word = random.choice(words)
guessed = []
attempts = 6
while attempts > 0:
display = ''.join([letter if letter in guessed else '_' for letter in word])
print(f'Word: {display}')
print(f'Attempts left: {attempts}')
if '_' not in display:
print('You won!')
break
guess = input('Guess: ').lower()
if guess in word and guess not in guessed:
guessed.append(guess)
print('Correct!')
else:
attempts -= 1
print('Wrong!')
else:
print(f'You lost! Word was: {word}')Expected Output:
Hangman game running
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code