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)
- random.choice(WORDS) picks one secret word from the list.
- guessed is a set that stores every letter the player has tried. A set ignores duplicates and checks 'in' very fast.
- The shown word is built with a generator: a guessed letter appears, every other letter becomes an underscore.
- all(...) checks if every letter of the word is guessed. If yes, the player wins and the function returns.
- .strip().lower() cleans the input, and len() plus isalpha() make sure exactly one letter was typed.
- A wrong letter increases wrong by 1. When wrong reaches MAX_WRONG, the loop ends and the player loses.
Concepts you practise
- random.choice
- sets
- generator expressions
- all()
- string methods
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()
Practice on PyDebug
After playing, turn the idea into a debugging habit with these free exercises: