The Wayback Machine - https://web.archive.org/web/20250102041214/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



Next Article
Article Tags :
Practice Tags :

Similar Reads

three90RightbarBannerImg