0% found this document useful (0 votes)
11 views1 page

Hangman Python Explained

This document describes a simple Hangman game implemented in Python, including the complete code and a detailed explanation of its functionality. The game randomly selects a word from a predefined list, allows the player to guess letters, and tracks the number of attempts remaining. The game concludes when the player either successfully guesses the word or runs out of attempts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views1 page

Hangman Python Explained

This document describes a simple Hangman game implemented in Python, including the complete code and a detailed explanation of its functionality. The game randomly selects a word from a predefined list, allows the player to guess letters, and tracks the number of attempts remaining. The game concludes when the player either successfully guesses the word or runs out of attempts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

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.

You might also like