In this tutorial, we’ll walk you through the process of creating a fully functional hangman game using Python.
Hangman is a word guessing game where players try to correctly guess a hidden word or phrase before a certain number of incorrect guesses. Players guess letters of the word one at a time. If the letter exists in the word, it will show up in the word, but if it’s not, it’s recorded as an incorrect guess.
Developing a Hangman game from scratch in Python is an excellent way for beginner programmers to practice and solidify their understanding of basic programming concepts like variables, loops, and conditional statements.
This tutorial covers everything from setting up the hangman game logic to handling user interaction and displaying the results on the console.
Steps for Hangman Game Implementation in Python
Here’s a summary of the steps you’ll need to complete to create your own hangman game with Python:
Step 1. Creating necessary data structures
The first step in developing a Hangman game is to create the required data structures. This includes creating the variables you’ll need for the game. To get you thinking on the right track, you’ll need to create variables to store:
- the word that the player needs to guess.
- the total number of false guesses.
- the total remaining lives or chances for the player.
Step 2. Creating the game loop
The game loop is the core of the Hangman game. It controls the flow of the game and checks for player input. The loop should continue until the player has correctly guessed the word or has run out of guesses.
Step 3. Implementing the guessing mechanism
The player should be able to input letters as their guesses. The game should check if the letter is in the word and if it is, reveal the letter in the word. The player loses a life if the letter is not in the word.
Step 4. Displaying the game state
The game should display the word with the correctly guessed letters filled in and the number of lives remaining. We won’t go over it here, but you could also store the incorrect guesses and display those somewhere separately on the console.
Step 5. End of the game
The game should end when the player has correctly guessed the word or has run out of lives. If the player has won, the game should congratulate them; if they lost, the game should show the word.
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
Python Code for Hangman Game
Here’s an example of a basic Python implementation of the Hangman game.
Step 1: Creating Necessary Data Structures
To develop a hangman game, you need a list of words, or a word corpus, which can be a simple list containing a few words or a full-fledged dictionary. The users will guess the word that is randomly picked from this corpus.
For this tutorial, we will use the NLTK library to download a resource called words
, a large corpus of English words. The following script does that.
import nltk
nltk.download('words')
from nltk.corpus import words
words.words()
Output:
'A',
'a',
'aa',
'aal',
'aalii',
'aam',
'Aani',
'aardvark',
'aardwolf',
'Aaron',
'Aaronic',
The above output shows that the corpus of words downloaded by the NLTK library also contains very small words.
We’ll only keep words that are between 7 and 9 characters (inclusive). We chose these values just for the sake of this example, but you can select words of different lengths if you prefer.
The following script imports the Python random library. Then it creates a list called words_list
, which contains all the words from the words.words()
corpus with lengths greater than six and less than 10. This is done using list comprehension, where the words are filtered based on length.
The script then uses the random.choice()
function to select a random word from the words_list
and assigns it to the variable word
. This is the word that we want the user to guess.
import random
#List of words to choose from
words_list = [w for w in words.words() if len(w)>6 and len(w)<10 ]
#Choose a random word from the list
word = random.choice(words_list)
print(word)
Output:
doubled
The random.choice()
function randomly picked the word
Next, you need to create a list of underscores which should be the same length as the length of the word to guess. This list will be updated by the words guessed by the user. We’ll need to define a variable that stores the number of lives (allowed wrong guesses) for the user, as well. The following script does that and gives players 6 lives.
#Create a list of underscores the same length as the word
display = ["_"] * len(word)
#Number of lives
lives = 6
Step 2: Creating the Game loop
The next step is to create the game loop. In the script in the next step, we’ll define a while loop that iterates until the display
list contains at least one underscore and the number of lives exceeds 0. This ensures that the game ends if no underscores remain in the display
list (the user guesses all the letters), or the number of lives decreases to 0 (the user uses all his lives).
Steps 3 & 4 : Implementing the Guessing Mechanism and Displaying Game State
This is the most crucial part of the game.
In the following code, inside the loop, we first ask the user to input a character. Next, we check if the character is present in the random word you generated in Step 1. If the character is present, we replace the underscore in the display
list with the character guessed by the user. After that, we print the display
list.
If the character guessed by the user is not present in the list, we decrease the number of lives by 1 and print a statement telling the user that he guessed the wrong character.
Steps 2, 3 & 4 are performed in the following script.
#Step 2: creating the game loop
while "_" in display and lives > 0:
# Get player's guess
guess = input("Guess a letter: ")
#Steps 3 & 4: Implementing the Guessing Mechanism and Displaying Game State
# Check if the letter is in the word
if guess in word:
# Reveal the letter in the word
for i in range(len(word)):
if word[i] == guess:
display[i] = guess
# Print the word with the correctly guessed letters
print(" ".join(display))
else:
lives -= 1
print("Incorrect. You have", lives, "lives remaining.")
print("=============================================")
Here is the output of the above script.
Output:
Step 5: End of the Game
Once the game loop ends, we check if the display
list contains an underscore. If the list does not contain an underscore, the user could guess the word correctly, and hence we print the message that the user correctly guessed the word. Otherwise, we print that the user could not correctly guess the word.
#Check if the player has won or lost
if "_" not in display:
print("Congratulations! You have correctly guessed the word.")
else:
print("Sorry, you ran out of lives. The word was", word + ".")
Output:
Congratulations! You have correctly guessed the word.
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.
Allowing User to Restart the Game
The code in the previous section is enough if you want to play the game once. You’ll have to rerun the script to continue playing the game. There’s a better way to do this, though.
You can use a while loop that surrounds the entire game code to allow the user to restart the game after the user wins or loses. Inside the while loop, you can add a condition to check if the player wants to play again. Here’s an example:
while True:
# List of words to choose from
words_list = [w for w in words.words() if len(w)>6 and len(w)<10 ]
# Choose a random word from the list
word = random.choice(words_list)
# Create a list of underscores the same length as the word
display = ["_"] * len(word)
# Number of lives
lives = 6
while "_" in display and lives > 0:
# Get player's guess
guess = input("Guess a letter: ")
# Check if the letter is in the word
if guess in word:
# Reveal the letter in the word
for i in range(len(word)):
if word[i] == guess:
display[i] = guess
# Print the word with the correctly guessed letters
print(" ".join(display))
else:
lives -= 1
print("Incorrect. You have", lives, "lives remaining.")
# Check if the player has won or lost
if "_" not in display:
print("Congratulations! You have correctly guessed the word.")
else:
print("Sorry, you ran out of lives. The word was", word + ".")
#ask the player if they want to play again
play_again = input("Do you want to play again? (yes/no)")
if play_again == "no":
break
Output:
In this example, the game will continue to loop as long as the player enters
That’s it! As you build your Python skills, you can make improvements to this code. Here are a few ideas for things you can do to improve this Python hangman game:
- Make the letter guesses case insensitive
- Only accept one character in the input field
- Only accept the input response of the character provided is a letter
- Add an option to guess the word in its entirety.
That’s one of the beauties of programming - there are always things you can do to build on your projects and make them even better! If you found this tutorial helpful, subscribe using the form below and we’ll send you more fun Python projects for all skill levels.
Code More, Distract Less: Support Our Ad-Free Site
You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.