← Back

Home › Code Lab › Hangman Game in Python

Hangman in Python — word guessing game, code and logic

Play a free Python Hangman word game in your browser, copy or download the code, and learn how the guessing logic works. · Level: Beginner · इसे Hindi में पढ़ें

Run the Python code

Output

    
  

How the logic works (free)

  1. random.choice(WORDS) picks one secret word from the list.
  2. guessed is a set that stores every letter the player has tried. A set ignores duplicates and checks 'in' very fast.
  3. The shown word is built with a generator: a guessed letter appears, every other letter becomes an underscore.
  4. all(...) checks if every letter of the word is guessed. If yes, the player wins and the function returns.
  5. .strip().lower() cleans the input, and len() plus isalpha() make sure exactly one letter was typed.
  6. A wrong letter increases wrong by 1. When wrong reaches MAX_WRONG, the loop ends and the player loses.

Concepts you practise

Full code (plain text)
import random

WORDS = ["python", "variable", "function", "loop", "string"]
MAX_WRONG = 6

def play_hangman():
    word = random.choice(WORDS)
    guessed = set()
    wrong = 0
    while wrong < MAX_WRONG:
        shown = " ".join(letter if letter in guessed else "_" for letter in word)
        print(f"\nWord: {shown}   Wrong guesses left: {MAX_WRONG - wrong}")
        if all(letter in guessed for letter in word):
            print("You won! The word was", word)
            return
        letter = input("Guess a letter: ").strip().lower()
        if len(letter) != 1 or not letter.isalpha():
            print("Please type exactly one letter.")
            continue
        if letter in guessed:
            print("You already guessed that letter.")
        elif letter in word:
            guessed.add(letter)
            print("Good guess!")
        else:
            guessed.add(letter)
            wrong += 1
            print("Wrong guess!")
    print("You lost. The word was", word)

play_hangman()

Extra tools

Step through every line of the code, or load the Level 2 version of this game with new rules and challenges. Both tools are free.

Practice on PyDebug

After playing, turn the idea into a debugging habit with these free exercises: