The Wayback Machine - https://web.archive.org/web/20240921213511/https://www.geeksforgeeks.org/hangman-game-python/
Open In App

Hangman Game in Python

Last Updated : 14 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Hangman Wiki:

The origins of Hangman are obscure meaning not discovered, but it seems to have arisen in Victorian times, ” says Tony Augarde, author of The Oxford Guide to Word Games. The game is mentioned in Alice Bertha Gomme’s “Traditional Games” in 1894 under the name “Birds, Beasts and Fishes.” The rules are simple; a player writes down the first and last letters of a word and another player guesses the letters in between. In other sources, [where?] the game is called “Gallows”, “The Game of Hangin”, or “Hanger”. 

Implementation:

This is a simple Hangman game using Python programming language. Beginners can use this as a small project to boost their programming skills and understanding logic.  

  1. The Hangman program randomly selects a secret word from a list of secret words. The random module will provide this ability, so line 1 in program imports it.
  2. The Game: Here, a random word (a fruit name) is picked up from our collection and the player gets limited chances to win the game.
  3. When a letter in that word is guessed correctly, that letter position in the word is made visible. In this way, all letters of the word are to be guessed before all the chances are over. 
  4. For convenience, we have given length of word + 2 chances. For example, word to be guessed is mango, then user gets 5 + 2 = 7 chances, as mango is a five-letter word.

Example

Python
# Python Program to illustrate
# Hangman Game
import random
from collections import Counter

someWords = '''apple banana mango strawberry 
orange grape pineapple apricot lemon coconut watermelon 
cherry papaya berry peach lychee muskmelon'''

someWords = someWords.split(' ')
# randomly choose a secret word from our "someWords" LIST.
word = random.choice(someWords)

if __name__ == '__main__':
    print('Guess the word! HINT: word is a name of a fruit')

    for i in word:
        # For printing the empty spaces for letters of the word
        print('_', end=' ')
    print()

    playing = True
    # List for storing the letters guessed by the player
    letterGuessed = ''
    chances = len(word) + 2
    correct = 0
    flag = 0
    try:
        while (chances != 0) and flag == 0:  # Flag is updated when the word is correctly guessed
            print()
            chances -= 1

            try:
                guess = str(input('Enter a letter to guess: '))
            except:
                print('Enter only a letter!')
                continue

            # Validation of the guess
            if not guess.isalpha():
                print('Enter only a LETTER')
                continue
            elif len(guess) > 1:
                print('Enter only a SINGLE letter')
                continue
            elif guess in letterGuessed:
                print('You have already guessed that letter')
                continue

            # If letter is guessed correctly
            if guess in word:
                # k stores the number of times the guessed letter occurs in the word
                k = word.count(guess)
                for _ in range(k):
                    letterGuessed += guess  # The guessed letter is added as many times as it occurs

            # Print the word
            for char in word:
                if char in letterGuessed and (Counter(letterGuessed) != Counter(word)):
                    print(char, end=' ')
                    correct += 1
                # If user has guessed all the letters
                # Once the correct word is guessed fully,
                elif (Counter(letterGuessed) == Counter(word)):
                    # the game ends, even if chances remain
                    print("The word is: ", end=' ')
                    print(word)
                    flag = 1
                    print('Congratulations, You won!')
                    break  # To break out of the for loop
                    break  # To break out of the while loop
                else:
                    print('_', end=' ')

        # If user has used all of his chances
        if chances <= 0 and (Counter(letterGuessed) != Counter(word)):
            print()
            print('You lost! Try again..')
            print('The word was {}'.format(word))

    except KeyboardInterrupt:
        print()
        print('Bye! Try again.')
        exit()

Output: 

Please run the program on your terminal.  

omkarpathak@omkarpathak-Inspiron-3542:~/Documents/
Python-Programs$ python P37_HangmanGame.py
Guess the word! HINT: word is a name of a fruit
_ _ _ _ _

Enter a letter to guess: m
_ _ m _ _
Enter a letter to guess: o
_ _ m o _
Enter a letter to guess: l
l _ m o _
Enter a letter to guess: e
l e m o _
Enter a letter to guess: n
l e m o n
Congratulations, You won!

Code Explanation:

  1. The code starts by importing the random module.
  2. This module provides a way to generate random numbers.
  3. Next, the code creates someWords, which is a list of fruit names.
  4. The list is split into spaces using the string ‘ ‘, and then each space is replaced with a letter.
  5. Next, the code randomly selects a secret word from our someWords list.
  6. This word will be used as the input for the game later on.
  7. The next part of the code checks to see if the user has entered an alpha character (a letter that appears in front of other letters).
  8. If not, then they are asked to enter only a letter.
  9. If they enter an alpha character, then it’s assumed that they want to guess at another letter in word .
  10. So, this part of the code checks to see if guess matches one of the letters in word .
  11. If it does, then chances is updated and flag is set to 1 .
  12. Otherwise, chances is decreased by 1 and flag remains at 0 .
  13. The next part of the code tries to guess at another letter in word .
  14. If guess isn’t valid (i.e., it doesn’t match any of the letters in word ), then print() prints out all empty spaces for letters in word , and
  15. The code starts by importing the random module.
  16. This module provides us with a number of useful functions, one of which is the choice function.
  17. This function allows us to randomly choose a secret word from our list of words.
  18. Next, we create some variables which will be used throughout the program.
  19. These include someWords , word and letterGuessed .
  20. letterGuessed will store the letter guessed by the player, while chances will store the number of times that the player has correctly guessed the word so far.
  21. correct will keep track of how many letters have been guessed so far and flag will indicate whether or not the player has guessed the word correctly.
  22. We then start looping through our list of words and randomly choosing a secret word from it.

Try it yourself Exercises: 

  • You can further enhance program by adding timer after every Guess
  • You can also give hints from the beginning to make the task a bit easier for user
  • You can also decrease the chance by one only if the player’s guess is WRONG. If the guess is right, 
    player’s chance is not reduced.

Hangman Game in Python – FAQs


How to Make Hangman Game in Python Using Tkinter

Creating a Hangman game using Tkinter in Python involves setting up a graphical user interface where the user can guess letters to figure out a hidden word. Below is a simplified version of such a game:

import tkinter as tk
import random

# List of words to guess
words = ['apple', 'banana', 'cherry', 'date', 'grape']

# Choose a random word
word = random.choice(words)
guessed = ['_' for _ in word] # List to keep track of guessed letters

def guess(letter):
if letter in word:
update_guessed(letter)
update_display()

def update_guessed(letter):
for index, char in enumerate(word):
if char == letter:
guessed[index] = letter

def update_display():
label.config(text=' '.join(guessed))
if '_' not in guessed:
label.config(text='You win!')

# Create the main window
root = tk.Tk()
root.title("Hangman Game")

# Create a label to show the word to guess
label = tk.Label(root, text=' '.join(guessed), font=('Helvetica', 24))
label.pack(pady=20)

# Create a frame to hold the buttons
frame = tk.Frame(root)
frame.pack()

# Create buttons for each letter
for ascii_code in range(97, 123): # ASCII codes for a-z
letter = chr(ascii_code)
btn = tk.Button(frame, text=letter.upper(), command=lambda l=letter: guess(l))
btn.pack(side='left')

# Run the application
root.mainloop()

What is Hangman Coding?

“Hangman coding” generally refers to implementing the Hangman game, where a player tries to guess a word by suggesting letters within a certain number of guesses. In coding, this game is often used to teach or demonstrate basic programming concepts like loops, conditionals, user input handling, and simple data structure management.

What is the Hardest Thing to Make in Python?

The difficulty of a project in Python depends on the complexity of the problem being solved and the programmer’s skill level. Advanced topics that can be challenging include:

  • Machine learning and deep learning systems.
  • Real-time data processing applications.
  • Large-scale web applications using asynchronous programming.
  • Integrating Python with other programming languages and systems in complex environments.

Is Hangman a 2 Player Game?

Traditionally, Hangman is a two-player game where one player thinks of a word, and the other tries to guess it by suggesting letters within a limited number of guesses. However, it can be adapted for a single player against a computer, where the computer randomly selects a word and the player guesses it.

How to Do a Guessing Game on Python?

Here’s a simple example of a number guessing game in Python:

import random

def guessing_game():
number = random.randint(1, 100) # Random number between 1 and 100
tries = 0
while True:
tries += 1
guess = int(input("Guess a number between 1 and 100: "))
if guess < number:
print("Too low!")
elif guess > number:
print("Too high!")
else:
print(f"Congratulations! You guessed the number in {tries} tries.")
break

guessing_game()

This game prompts the user to guess a random number between 1 and 100, providing feedback if the guess is too high or too low, and congratulates the player upon guessing correctly



Previous Article
Next Article

Similar Reads

Hangman Game with a GUI in Python
In this article, we'll be building the Hangman Game. To create the game's graphical user interface (GUI), we'll be using the Pygame library in Python. Pygame is a library commonly used for making graphical user interface games. So, let's dive into creating our Hangman Game with the help of Pygame! What is the Hangman Game?Hangman is a word-guessing
8 min read
Python implementation of automatic Tic Tac Toe game using random number
Tic-tac-toe is a very popular game, so let's implement an automatic Tic-tac-toe game using Python. The game is automatically played by the program and hence, no user input is needed. Still, developing an automatic game will be lots of fun. Let's see how to do this. NumPy and random Python libraries are used to build this game. Instead of asking the
5 min read
Color game using Tkinter in Python
TKinter is widely used for developing GUI applications. Along with applications, we can also use Tkinter GUI to develop games. Let's try to make a game using Tkinter. In this game player has to enter color of the word that appears on the screen and hence the score increases by one, the total time to play this game is 30 seconds. Colors used in this
4 min read
Rock, Paper, Scissor game - Python Project
In this article, we will see how we can create a rock paper and scissor game using Tkinter. Rock paper scissor is a hand game usually played between two people, in which each player simultaneously forms one of the three shapes with an outstretched hand. These shapes are “rock”, “paper”, and “scissors”. Game Winner Conditions Let there be a Player w
15+ min read
Python | Program to implement simple FLAMES game
Python is a multipurpose language and one can do literally anything with it. Python can also be used for game development. Let’s create a simple FLAMES game without using any external game libraries like PyGame. FLAMES is a popular game named after the acronym: Friends, Lovers, Affectionate, Marriage, Enemies, Sibling. This game does not accurately
6 min read
Python | Simple FLAMES game using Tkinter
Prerequisites: Introduction to TkinterProgram to implement simple FLAMES game Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and e
5 min read
21 Number game in Python
21, Bagram, or Twenty plus one is a game which progresses by counting up 1 to 21, with the player who calls "21" is eliminated. It can be played between any number of players. Implementation This is a simple 21 number game using Python programming language. The game illustrated here is between the player and the computer. There can be many variatio
11 min read
Python | Pokémon Training Game
Problem : You are a Pokémon trainer. Each Pokémon has its own power, described by a positive integer value. As you travel, you watch Pokémon and you catch each of them. After each catch, you have to display maximum and minimum powers of Pokémon caught so far. You must have linear time complexity. So sorting won't help here. Try having minimum extra
1 min read
Mastermind Game using Python
Given the present generation's acquaintance with gaming and its highly demanded technology, many aspire to pursue the idea of developing and advancing it further. Eventually, everyone starts at the beginning. Mastermind is an old code-breaking game played by two players. The game goes back to the 19th century and can be played with paper and pencil
8 min read
Introduction to pyglet library for game development in Python
Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc on Windows, Mac OS and Linux. This library is created purely in Python and it supports many features like windowing, user interface event handling, Joysticks, OpenGL graphics, loading images, and videos, and playing sounds and music.
2 min read
Tic Tac Toe Game using PyQt5 in Python
In this article , we will see how we can create a Tic Tac Toe game using PyQt5. Tic-tac-toe, noughts, and crosses, or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. Below
5 min read
Create a Simple Two Player Game using Turtle in Python
Prerequisites: Turtle Programming in Python TurtleMove game is basically a luck-based game. In this game two-players (Red &amp; Blue), using their own turtle (object) play the game. How to play The game is played in the predefined grid having some boundaries. Both players move the turtle for a unit distance.Now both players flip the coin:if HEAD, t
4 min read
Snake Water Gun game using Python and C
Snake Water Gun is one of the famous two-player game played by many people. It is a hand game in which the player randomly chooses any of the three forms i.e. snake, water, and gun. Here, we are going to implement this game using python. This python project is to build a game for a single player that plays with the computer Following are the rules
8 min read
Tic Tac Toe game with GUI using tkinter in Python
Tic-tac-toe (American English), noughts and crosses (British English), or Xs and Os is a paper-and-pencil game for two players, X and O, who take turns marking the spaces in a 3×3 grid. The player who succeeds in placing three of their marks in a horizontal, vertical, or diagonal row is the winner. tkinter Python library is used to create the GUI.
15+ min read
Quote Guessing Game using Web Scraping in Python
Prerequisite: BeautifulSoup Installation In this article, we will scrape a quote and details of the author from this site http//quotes.toscrape.com using python framework called BeautifulSoup and develop a guessing game using different data structures and algorithm. The user will be given 4 chances to guess the author of a famous quote, In every ch
3 min read
Python - Cows and Bulls game
Cows and Bulls is a pen and paper code-breaking game usually played between 2 players. In this, a player tries to guess a secret code number chosen by the second player. The rules are as follows: A player will create a secret code, usually a 4-digit number. This number should have no repeated digits.Another player makes a guess (4 digit number) to
3 min read
Game of Craps in Python
In this article, we are going to discuss how to create the Game of Craps using Python. Rules of the game: Two dices are required to play and a player rolls two six-sided dice and adds the numbers rolled together.If on the first roll a player encounters a total of 7 or 11 the player automatically wins, and if the player rolls a total of 2, 3, or 12
5 min read
Python - MCQ Quiz Game using Tkinter
Prerequisite: Python GUI – tkinter Python provides a standard GUI framework Tkinter which is used to develop fast and easy GUI applications. Here we will be developing a simple multiple-choice quiz in python with GUI. We will be creating a multiple choice quiz in Python with Tkinter. First, we will create a library named Quiz in the directory of yo
6 min read
KBC game using Python
In this article, we will make a KBC game with almost all the features in CLI(Command Line Interface) mode using Python. Features of the game:Random questions every timeFour lifelinesAudience Poll50:50Double dipFlip the questionMade with the help of Matplotlib and NumPy libraries of python.Bar graph for audience poll lifelineRules to play the game:T
15 min read
Python Arcade - Adding Bullets in Game
In this article, we will learn how to add bullets to a game in Arcade using Python. Adding Bullet In this example, we are going to add bullets to the screen. For this, we will use some functions: draw_text(): This function is used to draw text to the screen using Pyglet’s label. Syntax: arcade.draw_text(text, x, y, color, size, width, align, font_n
4 min read
Higher-Lower Game with Python
In this article, we will be looking at the way to design a game in which the user has to guess which has a higher number of followers and it displays the scores. Game Play:The name of some Instagram accounts will be displayed, you have to guess which has a higher number of followers by typing in the name of that account. Make sure you type the name
8 min read
Snake Game Using Tkinter - Python
For many years, players all across the world have cherished the iconic video game Snake. The player controls a snake that crawls around the screen while attempting to consume food, avoiding obstacles or running into its own tail. It is a straightforward but addictive game. The snake lengthens each time it consumes food, and the player must control
12 min read
Brick Breaker Game In Python using Pygame
Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by the number of blocks broken and each time the player
14 min read
Dice game using Turtle in Python
Dice Roll Game using python turtleThe simple python program implements the rolling of dice using the turtle library and random module of python. The turtle library is used to draw graphics and animations on the screen, while the random library is used to generate random numbers and random selections that can be used to control the behavior of the t
3 min read
Automate Chrome Dino Game using Python
For this article, we will be building a Python bot that can play the "Chrome Dino Offline Game". Chrome dino is a dinosaur game that launches itself on your web browser when there is no internet connection. For the introduction of the game, the dinosaur has to jump to avoid the approaching cactus or duck to avoid the bird. The first fundamental ste
7 min read
Blackjack console game using Python
Blackjack is a popular two-player card game that is played with a deck of standard playing cards around the world in casinos. The main criteria for winning this game are chance and strategy. The challenge of this game is to get as close to 21 points as possible without exceeding them. That is why it is also known as Twenty-One. In this article, we
6 min read
Create Bingo Game Using Python
A card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a simple bingo game in this lesson. The following i
9 min read
A Game of Anagrams in Python
Project idea:The aim of this project is to create a game in python in which the user is presented with an anagram of a word and has to guess the right word within a limited number of attempts. Features of Project: The user is given a fixed number of attempts to guess the correct word. The number of attempts is dependent on the length of the word.Af
4 min read
Conway's Game Of Life (Python Implementation)
Conways's Game Of Life is a Cellular Automation Method created by John Conway. This game was created with Biology in mind but has been applied in various fields such as Graphics, terrain generation,etc.. The "game" is a zero-player game, meaning that its evolution is determined by its initial state, requiring no further input. One interacts with th
5 min read
Create a 2D Game with Python and the Arcade Library
We have a task to create a 2D game with Python and the Arcade library. In this article, we will demonstrate how to create a 2D game using Python and the Arcade library. What is Arcade Library?The Arcade library in Python is a modern framework designed for creating 2D games and graphical applications. It provides a user-friendly and intuitive interf
7 min read
Article Tags :
Practice Tags :