Final Project - Hangman

Final Project

Build a Hangman Game

Project 2: Hangman

This is your second final project option. Hangman is a classic word guessing game that uses almost every concept covered in this course. You will work with lists, strings, loops, conditionals, functions and the random module all in one program.

You will build it step by step. Each step adds one piece of the game until you have a fully working Hangman that runs in the console.

By the end you will have a complete playable game written entirely by you.

What You Will Build

Your finished Hangman game will:

Concepts You Will Use

Step 1 — Set Up Your File

Create a new file in VS Code named hangman.py in your final project folder. Add the following at the top:

# Python Essentials - Final Project
# Hangman Game
# Your name here

import random

The import random line gives your program access to Python's built in random module. You will use it to pick a random word from your word bank.

Step 2 — Build Your Word Bank

Your words will be stored in a list. Each item is a string. Keep all words in lowercase to make comparisons easier later.

word_bank = [
    "python", "function", "variable", "dictionary", "iteration",
    "boolean", "argument", "parameter", "conditional", "recursion",
    "operator", "exception", "debugging", "inheritance", "algorithm",
    "compiler", "terminal", "indentation", "expression", "scope"
]

All of these words are from the course itself. A fitting choice for a Python Essentials project.

Step 3 — Pick a Random Word

Add a function called get_word() that picks and returns a random word from the word bank.

def get_word():
    '''
    Picks and returns a random word from the word bank.
    Returns: a string in lowercase.
    '''
    return random.choice(word_bank)

random.choice() takes a list and returns one random item from it. Test it by calling print(get_word()) and running the file a few times. You should see a different word each time.

Step 4 — Display the Word State

Add a function called display_word(word, guessed_letters) that shows the current state of the word. Correctly guessed letters are shown and unguessed letters appear as underscores.

def display_word(word, guessed_letters):
    '''
    Builds and returns a string showing guessed letters and underscores.
    word: the secret word as a string.
    guessed_letters: a list of letters the player has guessed so far.
    Returns: a string like "p _ t h _ n"
    '''
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter + " "
        else:
            display += "_ "
    return display.strip()

This function loops through every letter in the word. If the letter has been guessed it shows it. If not it shows an underscore. This is a for loop and a conditional working together.

Step 5 — Display the Welcome Message

Add a function called show_welcome() that prints a welcome message when the game starts.

def show_welcome():
    print("=" * 40)
    print("       PYTHON ESSENTIALS HANGMAN")
    print("=" * 40)
    print("Guess the word one letter at a time.")
    print("You have 6 lives. Good luck!")
    print("=" * 40)

Step 6 — Build the Main Game Loop

Add a function called play_game() that runs one full game. This is where everything comes together.

def play_game():
    word = get_word()
    guessed_letters = []
    incorrect_guesses = []
    lives = 6

    while lives > 0:
        print(f"\n{display_word(word, guessed_letters)}")
        print(f"Lives remaining: {lives}")
        print(f"Incorrect guesses: {', '.join(incorrect_guesses) if incorrect_guesses else 'none'}")

        guess = input("\nGuess a letter: ").lower().strip()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single letter.")
            continue

        if guess in guessed_letters or guess in incorrect_guesses:
            print(f"You already guessed '{guess}'. Try a different letter.")
            continue

        if guess in word:
            guessed_letters.append(guess)
            print(f"Good guess!")

            if all(letter in guessed_letters for letter in word):
                print(f"\n{'=' * 40}")
                print(f"  You won! The word was: {word.upper()}")
                print(f"{'=' * 40}")
                return
        else:
            incorrect_guesses.append(guess)
            lives -= 1
            print(f"Wrong! '{guess}' is not in the word.")

    print(f"\n{'=' * 40}")
    print(f"  Game over. The word was: {word.upper()}")
    print(f"{'=' * 40}")

Step 7 — Ask to Play Again

Add the same ask_play_again() function used in the quiz game. It keeps asking until the player types yes or no.

def ask_play_again():
    while True:
        choice = input("\nPlay again? (yes / no): ").lower().strip()
        if choice == "yes":
            return True
        elif choice == "no":
            return False
        else:
            print("Please type yes or no.")

Step 8 — Wire It All Together

Add the main() function that ties the whole game together and call it at the bottom of the file.

def main():
    show_welcome()

    while True:
        play_game()

        if not ask_play_again():
            print("\nThanks for playing. Goodbye!")
            break

main()

Run the file and play a full game. If something does not work as expected go back through each step and check your indentation and function calls carefully.

The Complete Game

Here is the full completed game for reference. Only look at this after you have tried building it yourself.

# Python Essentials - Final Project
# Hangman Game
# Your name here

import random

word_bank = [
    "python", "function", "variable", "dictionary", "iteration",
    "boolean", "argument", "parameter", "conditional", "recursion",
    "operator", "exception", "debugging", "inheritance", "algorithm",
    "compiler", "terminal", "indentation", "expression", "scope"
]


def get_word():
    return random.choice(word_bank)


def display_word(word, guessed_letters):
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter + " "
        else:
            display += "_ "
    return display.strip()


def show_welcome():
    print("=" * 40)
    print("       PYTHON ESSENTIALS HANGMAN")
    print("=" * 40)
    print("Guess the word one letter at a time.")
    print("You have 6 lives. Good luck!")
    print("=" * 40)


def play_game():
    word = get_word()
    guessed_letters = []
    incorrect_guesses = []
    lives = 6

    while lives > 0:
        print(f"\n{display_word(word, guessed_letters)}")
        print(f"Lives remaining: {lives}")
        print(f"Incorrect guesses: {', '.join(incorrect_guesses) if incorrect_guesses else 'none'}")

        guess = input("\nGuess a letter: ").lower().strip()

        if len(guess) != 1 or not guess.isalpha():
            print("Please enter a single letter.")
            continue

        if guess in guessed_letters or guess in incorrect_guesses:
            print(f"You already guessed '{guess}'. Try a different letter.")
            continue

        if guess in word:
            guessed_letters.append(guess)
            print(f"Good guess!")

            if all(letter in guessed_letters for letter in word):
                print(f"\n{'=' * 40}")
                print(f"  You won! The word was: {word.upper()}")
                print(f"{'=' * 40}")
                return
        else:
            incorrect_guesses.append(guess)
            lives -= 1
            print(f"Wrong! '{guess}' is not in the word.")

    print(f"\n{'=' * 40}")
    print(f"  Game over. The word was: {word.upper()}")
    print(f"{'=' * 40}")


def ask_play_again():
    while True:
        choice = input("\nPlay again? (yes / no): ").lower().strip()
        if choice == "yes":
            return True
        elif choice == "no":
            return False
        else:
            print("Please type yes or no.")


def main():
    show_welcome()

    while True:
        play_game()

        if not ask_play_again():
            print("\nThanks for playing. Goodbye!")
            break

main()

Challenges — Take It Further

Challenge 1 — Draw the Hangman

  • Create a list of strings where each item is one stage of the hangman drawing
  • Print the correct stage based on the number of lives remaining
  • This uses list indexing and ASCII art

Challenge 2 — Add a Hint

  • Give the player the option to ask for a hint once per game
  • The hint reveals one random unguessed letter
  • Use random.choice() on the unguessed letters

Challenge 3 — Track Win and Loss Count

  • Create global variables wins = 0 and losses = 0
  • Update them after each game using the global keyword
  • Display the totals at the start of each new game

Challenge 4 — Add Difficulty Levels

  • Ask the player to choose easy, medium or hard before the game starts
  • Easy gives 8 lives, medium gives 6 and hard gives 4
  • Filter the word bank by word length for each difficulty

What You Just Demonstrated

By completing this project you have shown you can:

That is not a beginner skill set anymore.

Don't Forget to commit and Push!