Untitled
public
Oct 01, 2024
Never
18
1 # Hangman Game 2 3 # Import the random module to generate random words 4 import random 5 6 # List of words to choose from 7 words = ["apple", "banana", "cherry", "date", "elderberry"] 8 9 # Choose a random word from the list 10 word = random.choice(words) 11 12 # Create a list to store the guessed letters 13 guessed_letters = [] 14 15 # Create a list to store the correct letters 16 correct_letters = [] 17 18 # Create a variable to store the number of attempts 19 attempts = 0 20 21 # Print the word with underscores representing the letters 22 print(" ".join("_" * len(word))) 23 24 while True: 25 # Ask the user to guess a letter 26 guess = input("Guess a letter: ") 27 28 # Check if the letter has already been guessed 29 if guess in guessed_letters: 30 print("You already guessed that letter!") 31 else: 32 # Add the letter to the list of guessed letters 33 guessed_letters.append(guess) 34 35 # Check if the letter is in the word 36 if guess in word: 37 # Add the letter to the list of correct letters 38 correct_letters.append(guess) 39 print("Correct! The letter '{}' is in the word.".format(guess)) 40 else: 41 # Increment the number of attempts 42 attempts += 1 43 print("Incorrect. The letter '{}' is not in the word.".format(guess)) 44 45 # Print the word with the correct letters filled in 46 print(" ".join([letter if letter in correct_letters else "_" for letter in word])) 47 48 # Check if the user has won or lost 49 if all(letter in correct_letters for letter in word): 50 print(" Congratulations! You guessed the word '{}'!".format(word)) 51 break 52 elif attempts >= 6: 53 print("Sorry, you didn't guess the word. The word was '{}'.".format(word)) 54 break