import random # List of words to choose from words = ['apple', 'banana', 'orange', 'pear', 'grape', 'kiwi', 'pineapple'] # Select a random word from the list word = random.choice(words) # Create an empty list to store the correctly guessed letters correct_guesses = [] # Create an empty list to store the incorrectly guessed letters incorrect_guesses = [] # Set the number of guesses allowed num_guesses = 6 # Loop until the player has used all their guesses or has guessed the word while num_guesses > 0 and set(word) != set(correct_guesses): # Print the word with underscores in place of unguessed letters print(' '.join([letter if letter in correct_guesses else '_' for letter in word])) # Print the incorrect guesses so far print('Incorrect guesses:', ', '.join(incorrect_guesses)) # Ask the player to guess a letter guess = input('Guess a letter: ').lower() # Check if the letter has already been guessed if guess in correct_guesses or guess in incorrect_guesses: print('You have already guessed that letter.') # Check if the letter is in the word elif guess in word: print('Good guess!') correct_guesses.append(guess) # If the letter is not in the word, add it to the list of incorrect guesses else: print('Sorry, that letter is not in the word.') incorrect_guesses.append(guess) num_guesses -= 1 # Check if the player has won or lost if set(word) == set(correct_guesses): print('Congratulations, you guessed the word:', word) else: print('Sorry, you ran out of guesses. The word was:', word)