Python Program for a Hangman Game
Intermediate · Games and random numbers
In hangman, one player thinks of a word and the other guesses it one letter at a time. Each wrong letter costs a life, and the guesser wins by finding every letter before the lives run out. This program plays a whole game from a list of guesses and shows the word, with blanks, after every turn.
Program
'e' is not in the word, lives left: 5 Word: _ _ _ _ _ _ 'o' is in the word! Word: _ _ _ _ o _ 'a' is not in the word, lives left: 4 Word: _ _ _ _ o _ 't' is in the word! Word: _ _ t _ o _ 'o' was already tried 's' is not in the word, lives left: 3 Word: _ _ t _ o _ 'p' is in the word! Word: p _ t _ o _ 'n' is in the word! Word: p _ t _ o n 'y' is in the word! Word: p y t _ o n 'h' is in the word! Word: p y t h o n You win! The word was python
How it works
secretis the word to guess, andguessesstands in for the letters a player would type, one per turn.- Each new letter is added to
guessed; a letter that was tried before is skipped, so the second "o" costs no life. - A letter that is not in the word costs one life, from a starting total of 6.
- After every guess the word is shown with
_for each letter not found yet, by checking every letter ofsecretagainstguessed. - The game ends in a win when no
_is left, or in a loss whenlivesreaches 0; here the player wins with 3 lives to spare.
Another way to write it
A losing game, using a set and a function
Guess a: _ a _ a _ a lives: 3 Guess e: _ a _ a _ a lives: 2 Guess i: _ a _ a _ a lives: 1 Guess o: _ a _ a _ a lives: 0 Game over! The word was banana
A set is a natural fit for guessed letters, since each letter only needs to be stored once. With only 3 lives the player runs out before finding the b, so this game shows the losing end.
Try it yourself
Set lives to 3 and run the game again to see how it ends when the player runs out of lives.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises