Create Hangman Game
Hangman:
Hangman is a classic word-guessing game. The computer selects a word, and the player has to guess the letters one by one. For each incorrect guess, a part of the hangman is drawn.
import random
# List of words to choose from
words = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]
# Select a random word
word = random.choice(words)
# Track the guessed letters
guessed_letters = []
# Function to display the word with underscores for missing letters
def display_word():
for letter in word:
if letter in guessed_letters:
print(letter, end=" ")
else:
print("_", end=" ")
print()
print("Let's play Hangman!")
while True:
display_word()
guess = input("Guess a letter: ").lower()
if guess in guessed_letters:
print("You already guessed that letter!")
else:
guessed_letters.append(guess)
if guess in word:
print("Correct guess!")
else:
print("Wrong guess!")
if set(word) <= set(guessed_letters):
print("Congratulations! You guessed the word:", word)
break