Hangman Game in Python: Build and Code Tutorial for Beginners

 

The Hangman Game in Python

The Hangman game is a timeless word-guessing challenge that has entertained people for generations. In this tutorial, we’ll show you how to bring this classic game to life using Python. You'll learn the basics of handling strings, loops, and conditional statements, and by the end, you’ll have a fully functional Hangman game to test your programming skills. Perfect for beginners, this Python Hangman game also includes limited attempts, hints, and a step-by-step explanation to make learning both fun and interactive! 

 

Hangman Game in Python

 

 

Here's a detailed breakdown of each part of the Hangman game code:

 

1. Importing Required Libraries

import random

 

- We import the random module to randomly select a word from the list of words. This makes each game different as the word to guess changes each time.

 

2. Setting Up Words List

words = ["python", "hangman", "coding", "program", "software"]

 

- We define a list called words that contains possible words for the game. The player will try to guess one of these words.

 

3. Selecting a Random Word and Getting Its Length

word = random.choice(words)
word_length = len(word)

 

- We use random.choice(words) to select a random word from the words list and store it in the word variable.

 

4. Identifying the First, Middle, and Last Letters

first_letter = word[0]
middle_letter = word[word_length // 2]
last_letter = word[-1]

 

5. Creating the Initial Display Word

display_word = list('_' * word_length)
display_word[0] = first_letter
display_word[word_length // 2] = middle_letter
display_word[-1] = last_letter

 

6. Setting Up Maximum Attempts and Initializing Attempt Counter

max_attempts = 5
attempts = 0

 

7. Displaying the Initial Game State

print("Welcome to Hangman!")
print("Guess the word:", ' '.join(display_word))

 

8. Game Loop for Guessing

while attempts < max_attempts:

 

Inside the Loop

1. Getting User's Guess
guess = input("Enter your guess (one letter): ").lower()
 
2. Checking if Guess is Correct
 
if guess in word and guess not in display_word:
 
3. Revealing the Guessed Letter in the Word
for idx, letter in enumerate(word):
    if letter == guess:
        display_word[idx] = guess
print("Good guess:", ' '.join(display_word))
 
4. Handling Incorrect Guesses
else:
    attempts += 1
    print(f"Incorrect guess! Attempts left: {max_attempts - attempts}")
 
5. Checking if Player Has Guessed the Word
if '_' not in display_word:
    print("Congratulations! You've guessed the word:", word)
    break

 

9. Handling Loss Scenario

else:
print("Game over! You've run out of attempts. The word was:", word)


  • Five Attempt Limit: The player has only five attempts to guess the letters.
  • Hint Display: The first, middle, and last letters of the word are shown at the start.
  • Victory Condition: The player wins if they guess all letters within five attempts.
  • Loss Condition: The game ends if they reach five incorrect guesses without completing the word.


Read Also:

 

 

Source code:


 import random

# List of words for the hangman game
words = ["python", "hangman", "coding", "program", "software"]

# Randomly select a word
word = random.choice(words)
word_length = len(word)

# Determine the indices for the first, middle, and last letters
first_letter = word[0]
middle_letter = word[word_length // 2]
last_letter = word[-1]

# Create a partially filled word for display, with blanks for unguessed letters
display_word = list('_' * word_length)
display_word[0] = first_letter
display_word[word_length // 2] = middle_letter
display_word[-1] = last_letter

# Set the maximum number of guesses allowed
max_attempts = 5
attempts = 0

# Print the starting display word
print("Welcome to Hangman!")
print("Guess the word:", ' '.join(display_word))

# Game loop for up to 5 attempts
while attempts < max_attempts:
    guess = input("Enter your guess (one letter): ").lower()
    
    # Check if the guessed letter is in the word and not already revealed
    if guess in word and guess not in display_word:
        # Reveal all occurrences of the guessed letter
        for idx, letter in enumerate(word):
            if letter == guess:
                display_word[idx] = guess
        print("Good guess:", ' '.join(display_word))
    else:
        attempts += 1
        print(f"Incorrect guess! Attempts left: {max_attempts - attempts}")
    
    # Check if the player has guessed the entire word
    if '_' not in display_word:
        print("Congratulations! You've guessed the word:", word)
        break
else:
    print("Game over! You've run out of attempts. The word was:", word)

  


Output:-




Welcome to Hangman!
Guess the word: p _ _ h _ n
Enter your guess (one letter): y
Good guess: p y _ h _ n
Enter your guess (one letter): t
Good guess: p y t h _ n
Enter your guess (one letter): o
Good guess: p y t h o n
Congratulations! You've guessed the word: python



End of Game and Conclusion:

  • If there are no underscores left in display, the player wins, and a message is displayed.
  • If lives reach zero, the player loses, and the correct word is revealed.

 

This code provides a basic structure for the Hangman game and can be easily expanded to add features like hinting or multiple rounds.

Previous Post Next Post