Hangman Game in Python (With Explanation)
This document contains a simple Hangman game written in Python along with a step-by-step
explanation of how the code works.
Python Code:
import random
words = ["python", "programming", "hangman", "developer", "computer"]
word = [Link](words)
guessed_word = ["_"] * len(word)
guessed_letters = []
attempts = 6
print("Welcome to Hangman!")
while attempts > 0 and "_" in guessed_word:
print("\nWord:", " ".join(guessed_word))
print("Guessed letters:", ", ".join(guessed_letters))
print("Attempts left:", attempts)
guess = input("Enter a letter: ").lower()
if guess in guessed_letters:
print("You already guessed that letter!")
continue
guessed_letters.append(guess)
if guess in word:
for i in range(len(word)):
if word[i] == guess:
guessed_word[i] = guess
print("Correct guess!")
else:
attempts -= 1
print("Wrong guess!")
if "_" not in guessed_word:
print("\nCongratulations! You guessed the word:", word)
else:
print("\nGame Over! The word was:", word)
Explanation:
1. The random module is used to select a random word from a list.
2. A list of words is defined for the game.
3. One word is chosen randomly.
4. Blank underscores represent each letter of the word.
5. A list keeps track of guessed letters.
6. The player has 6 attempts.
7. A loop runs until the player wins or loses.
8. The program checks whether the guessed letter is correct or not.
9. If correct, the word updates; if wrong, attempts decrease.
10. The game ends with a win or lose message.