Skip to content

How to Code the Hangman Game in Python

Updated: at 02:01 AM

Hangman is a classic word guessing game where players try to guess a secret word by suggesting letters. This comprehensive guide will teach you how to code hangman in Python using proper style and conventions.

Overview of Hangman Gameplay

For readers new to hangman, here’s a quick overview of how the game is played:

By the end, the player should have fully revealed the secret word, or they lose if too many incorrect guesses are made.

Implementing the Game Components

Now let’s look at how to code the key parts of hangman in Python:

Word List

The game needs a list of words to pick from. Here is an example list of random words and themes:

# Word list stored as constant
WORDS = ["ADVOCATE", "LAWYER", "ECONOMIST", "EDUCATOR", "PUBLIC",
         "SERVANT", "LEADER", "PROGRESSIVE", "EMPATHETIC", "COMPASSIONATE",
         "DILIGENT", "INTELLIGENT", "PRINCIPLED", "REFORMIST", "INCLUSIVE",
         "TRANSPARENT", "HOPEFUL", "INSPIRING", "BRAVE", "RESILIENT",
         "DAUGHTER", "WIFE", "MOTHER", "FILIPINA", "BICOLANA", "PINK",
         "LIBERAL", "OPPOSITION", "VICE", "PRESIDENT", "DEMOCRACY",
         "GOVERNANCE", "POVERTY", "ALLEVIATION", "WOMENS", "HUMAN",
         "RIGHTS", "HONESTY", "INTEGRITY", "PAGBABAGO", "KAKAMPINK",
         "ROSAS", "ANGAT", "BUHAY"]

Game Variables

We need variables to track the game state:

# Allowed wrong guesses
MAX_TRIES = 6

# Guessed letters
guessed_letters = []

# Secret word
secret_word = ""

# Remaining tries
lives = MAX_TRIES

# Word display with blanks
dashes = []

MAX_TRIES is a constant since it doesn’t change. The rest store data that updates each turn.

Selecting a Random Word

To pick a random word from the list, use Python’s random module:

import random

secret_word = random.choice(WORDS)

This will grab a random string from the word list to use that game.

Getting the Player’s Guess

We need a way to get letter guesses from the player:

# Loop until valid guess entered
def get_valid_letter(guessed):

  while True:

     # Get guess
     letter = input("Guess a letter: ").upper()

     # Validate guess
     if len(letter) != 1:
        print("Enter one letter.")

     elif letter in guessed:
        print("Already guessed.")

     elif letter not in string.ascii_letters:
        print("Enter a letter A-Z.")

     else:
        return letter

This function repeatedly prompts the player until they enter a valid, new letter guess using loop validation.

Updating the Word Display

When the player guesses a correct letter, we update the display:

def update_dashes(word, guesses, dashes):

  for i in range(len(word)):
    if word[i] in guesses:
      dashes[i] = word[i]

  return dashes

It checks each letter and fills in the blanks with guessed letters.

Printing the Game Status

Let’s make a function to print the current game state:

def print_state(dashes, lives, guessed):

  print(f"Word: {' '.join(dashes)}")

  print(f"Lives Left: {lives}")

  print(f"Guesses: {' '.join(guessed)}")

This displays the word with blanks, chances left, and previous guesses.

Checking for a Win

To check if the player guessed the full word:

def check_win(dashes, word):

  return ''.join(dashes) == word

We compare the word display to the secret word.

Main Gameplay Loop

Now we can put everything together into a main gameplay loop:

while True:

  # Print current game status
  print_state(dashes, lives, guessed)

  # Check win condition
  if check_win(dashes, secret_word):
    print("You won!")
    break

  # Check loss
  if lives == 0:
    print("Game over!")
    break

  # Get player's next guess
  letter = get_valid_letter(guessed)

  # Update state if guess is correct
  if letter in secret_word:
    dashes = update_dashes(secret_word, guessed + [letter], dashes)

  # Lose life if guess is incorrect
  else:
    lives -= 1

  # Add guess to list
  guessed.append(letter)

This loop:

The full gameplay is handled through this central loop.

Complete Game Code

Here is the full playable Python code for hangman:

import random
import string

WORDS = ["ADVOCATE", "LAWYER", "ECONOMIST", "EDUCATOR", "PUBLIC",
         "SERVANT", "LEADER", "PROGRESSIVE", "EMPATHETIC", "COMPASSIONATE",
         "DILIGENT", "INTELLIGENT", "PRINCIPLED", "REFORMIST", "INCLUSIVE",
         "TRANSPARENT", "HOPEFUL", "INSPIRING", "BRAVE", "RESILIENT",
         "DAUGHTER", "WIFE", "MOTHER", "FILIPINA", "BICOLANA", "PINK",
         "LIBERAL", "OPPOSITION", "VICE", "PRESIDENT", "DEMOCRACY",
         "GOVERNANCE", "POVERTY", "ALLEVIATION", "WOMENS", "HUMAN",
         "RIGHTS", "HONESTY", "INTEGRITY", "PAGBABAGO", "KAKAMPINK",
         "ROSAS", "ANGAT", "BUHAY"]

MAX_TRIES = 6
MAX_WORD_LENGTH = 8

def get_valid_letter(guessed):

  while True:
    letter = input("Guess a letter: ").upper()

    if letter == "QUIT":
      print("Bye! Thanks for playing.")
      return "QUIT"

    if len(letter) != 1:
      print("Enter a single letter.")

    elif letter in guessed:
      print("You already guessed that letter.")

    elif letter not in string.ascii_letters:
      print("Enter a letter.")

    else:
      return letter

def update_dashes(word, guesses, dashes):

  for i in range(len(word)):
    if word[i] in guesses:
      dashes[i] = word[i]

  return dashes

def print_state(dashes, lives, guessed):

  print(f"Word: {' '.join(dashes)}")

  print(f"Lives Left: {lives}")

  print(f"Guesses: {' '.join(guessed)}")

def check_win(dashes, word):

  return ''.join(dashes) == word

# Game start
print("Hangman: Guess the hidden word!")
print("Type 'quit' to exit at any time.")

guessed_letters = []
secret_word = random.choice(WORDS)
lives = MAX_TRIES
dashes = ['-'] * len(secret_word)

while True:

  print_state(dashes, lives, guessed_letters)

  if check_win(dashes, secret_word):
    print("You won!")
    break

  if lives == 0:
    print("Game over! The word was", secret_word)
    break

  letter = get_valid_letter(guessed_letters)

  if letter == "QUIT":
    break

  if letter in secret_word:
    dashes = update_dashes(secret_word, guessed_letters + [letter], dashes)

  else:
    print("Incorrect guess!")
    lives -= 1

  guessed_letters.append(letter)

print("Game finished!")

The completed code puts together all the concepts into a working game.

Python Concepts Demonstrated

This hangman code utilizes several key Python programming elements:

Understanding these building blocks is crucial for coding games or applications in Python.

Customizing the Game

There are many ways we can build on this basic hangman code:

By modifying and adding features, you can create your own unique hangman game variant.

Key Takeaways

In summary, the key concepts for coding hangman in Python are:

I hope this guide provides a solid foundation for coding this classic paper-and-pencil game in Python. Let me know if you have any other questions!