Hangman Game

Devise a Python program to implement the Hangman Game.

import random

# List of words for the game

word_list = ["apple", "banana", "mango",  "orange", "grape"]

 

# Select a random word from the list

secret_word = random.choice(word_list)

 

# Initialize variables

guessed_letters = []

attempts = 6

 

# Main game loop

while attempts > 0:

    display_word = "".join([letter if letter in guessed_letters else "_" for letter in secret_word])

   

    if display_word == secret_word:

        print("You won! The word is:", secret_word)

        break

   

    print("Word:", display_word)

    print("Attempts left:", attempts)

   

    guess = input("Guess a letter: ").lower()

   

    if guess in guessed_letters:

        print("You already guessed that letter.")

        continue

   

    guessed_letters.append(guess)

   

    if guess not in secret_word:

        print("Incorrect guess.")

        attempts -= 1

 

if attempts == 0:

    print("Out of attempts! The word was:", secret_word)

 

OUTPUT

 

Word: _____

Attempts left: 6

Guess a letter: t

Incorrect guess.

Word: _____

Attempts left: 5

Guess a letter: a

Word: __a__

Attempts left: 5

Guess a letter: p

Word: __ap_

Attempts left: 5

Guess a letter: e

Word: __ape

Attempts left: 5

Guess a letter: g

Word: g_ape

Attempts left: 5

Guess a letter: r

You won! The word is: grape