Hangman Game (Code) in Python

← Back to Projects

Hangman Game in Python

About the project: create a new Python project for a classic Hangman game.


The game will select a random word from a predefined list. You'll have to guess letters one at a time to reveal the word. Each incorrect guess will bring you closer to losing the game.


Below Python script is a complete, playable Hangman game.


How to use this Hangman Game:

  • Run the Python script.
  • When you run it, you can start guessing letters. The game will keep track of your correct and incorrect guesses and will let you know when you've won or lost.
  • You can play as many times as you like.


Project Level: Beginner

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE)




# hangman_game.py

import random

def get_random_word():
    """
    Returns a random word from a predefined list.
    You can easily modify this list to change the words in the game.
    """
    word_list = ["python", "hangman", "computer", "programming", "developer", "keyboard", "algorithm"]
    return random.choice(word_list).upper()

def play_game():
    """
    Main function to run a single game of Hangman.
    """
    word_to_guess = get_random_word()
    guessed_letters = set()
    incorrect_guesses = 0
    max_incorrect_guesses = 6

    print("--- Python Hangman Game ---")
    print("Guess the word one letter at a time.")
    print(f"You have {max_incorrect_guesses} incorrect guesses before you lose.")

    while incorrect_guesses < max_incorrect_guesses:
        # Display the current state of the word
        display_word = ""
        for letter in word_to_guess:
            if letter in guessed_letters:
                display_word += letter + " "
            else:
                display_word += "_ "
        
        print("\n" + display_word)

        # Check for a win
        if "_" not in display_word:
            print("\nCongratulations! You won!")
            print(f"The word was: {word_to_guess}")
            break

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

        if len(guess) != 1 or not guess.isalpha():
            print("Invalid input. Please enter a single letter.")
            continue
        
        if guess in guessed_letters:
            print("You already guessed that letter. Try another one.")
            continue

        guessed_letters.add(guess)

        if guess in word_to_guess:
            print(f"Good guess! '{guess}' is in the word.")
        else:
            incorrect_guesses += 1
            print(f"Incorrect guess. '{guess}' is not in the word.")
            print(f"You have {max_incorrect_guesses - incorrect_guesses} incorrect guesses left.")
    
    else: # This block executes if the while loop finishes without a 'break'
        print("\nGame over! You ran out of guesses.")
        print(f"The word was: {word_to_guess}")


def main():
    """
    Runs the Hangman game and allows the user to play multiple times.
    """
    while True:
        play_game()
        play_again = input("\nDo you want to play again? (yes/no): ").lower()
        if play_again != 'yes':
            print("Thanks for playing! Goodbye.")
            break

# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()