Code Your Own Hangman Game with Python | Step by Step

Kenny Brast
13 min readNov 10, 2023

How to use Python to create a classic word game

Hello! I’ve got a thrilling journey for your mind lined up. It’s a little something that’ll tickle your brain cells and ignite your creativity. We’re going to use Python to construct a hangman game that runs in the command line. How does that sound?

You may be wondering, what exactly is this hangman game? What’s the command line for? What about Python? Fear not! I’ll break down everything so it’s simple to grasp and enjoyable to follow.

Hangman is a classic word game where you have to guess a secret word by guessing one letter at a time. Guessing a letter that’s in the word will result in it showing up on the screen. However, guessing a letter that’s not in the word will cost you one of your attempts. Losing all your attempts means losing the game. On the other hand, guessing the word before running out of attempts leads to a win. Simple, right?

A command line is a way of interacting with your computer using text commands. You type in a command, and the computer does what you tell it to do. This tool is potent, capable of a multitude of tasks ranging from generating files and directories to executing programs and scripts.

Python is a programming language that enables the creation of all kinds of applications, encompassing everything from websites and games to data analysis and machine learning. It’s a joy to use and holds a high popularity among developers. Python is also the chosen language for crafting our hangman game.

Prerequisites

Before you start coding your hangman game, you need to make sure you have the following things installed on your computer:

Once these are installed, you’re ready to start coding your hangman game. Let’s go!

Setting up Visual Studio Code for Python

To use Visual Studio Code for Python, you need to install the Python extension and select the Python interpreter. Here’s how you do it:

  • Launch Visual Studio Code and open a folder for your Python workspace by going to File > Open… and selecting or creating a folder. This will be your Python workspace.
  • Open the Command Palette by pressing Shift, Command and P keys, or by going to View > Command Palette. Then type and select Python: Select Interpreter.
  • From the list of interpreters, select the appropriate Python 3 interpreter. This action will create a folder called .vscode inside your workspace, which stores the settings specific to the workspace. In this folder, you can find a file called settings.json, which contains the Python interpreter path.
  • At the bottom right corner of the Visual Studio Code window, you can see the Python version as well.

Visual Studio Code is now ready to interpret and run Python code. It’s time to create some Python source code in Visual Studio Code and check it.

Creating your first Python code in Visual Studio Code

In this section, you’ll create a simple Python code that prints a message on the screen. Here’s how you do it:

  • In the Explorer panel, press the New File icon against the workspace folder. Enter the name of the file with the extension .py, such as first.py.
  • In the newly created file, enter some Python code. For example, I used the code below, where a string value is assigned to a variable and the variable is passed as a parameter to the print function. While typing the source code, you can see the IntelliSense kicking in, showing you the autocomplete and function parameter value functionality. This is an indication that the settings we have done before were correct.
message = "Hello Python World!.."
print(message)
  • To run this code, right-click somewhere in the editor and select Run Python File in Terminal. This action will open the terminal panel at the bottom and run the Python file against the selected interpreter. The result will be like this:

Congratulations! You’ve just created and run your first Python code in Visual Studio Code. Let’s move on to creating the real hangman game.

Building the Hangman Game

In this section, you’ll learn how to use Python to code your hangman game, step by step. You’ll use some of the basic concepts and features of Python, such as variables, data types, functions, loops, conditions, and modules. Don’t worry if you’re not familiar with them, I’ll explain them as we go along. Just follow along and have fun.

Creating a Python file

First, you need to create a Python file for your game. You can do this in Visual Studio Code by following these steps:

  • Open Visual Studio Code and create a new folder for your Python workspace by going to File > Open… and selecting or creating a folder. This will be your Python workspace.
  • In the Explorer panel, press the New File icon against the workspace folder. Enter the name of the file with the extension .py, such as hangman.py.
  • You should see a blank file opened in the editor. This is where you will write your Python code for the game.

Here’s a screenshot of how it looks like:

Importing the modules

The next thing you need to do is import some modules that we’re going to use in our game. Modules are files that contain Python code that can be reused in other programs. Python comes with a lot of built-in modules that provide various functionalities, such as math, random, os, etc. You can also create your own modules or use modules created by other developers.

To import a module, you use the import statement, followed by the name of the module. For example, to import the math module, you write import math. You can also import specific parts of a module, such as a function or a constant, using the from keyword. For example, to import the sqrt function from the math module, you write from math import sqrt.

For our game, we’ll need three modules: os, random, and string. We’ll use the os module to clear the screen, the random module to pick a random word, and the ascii_letters constant from the string module to check the user’s input. Here’s how you import them:

# Import modules
import os
import random
from string import ascii_letters

Defining the words and the attempts

Next, we need to define a list of words that the user will have to guess. You can use any words you like, but I’m going to use some animals for this example. To create a list in Python, you use square brackets and separate the items with commas. For example, to create a list of colors, you write colors = ["red", "green", "blue"].

We’ll also define a variable called max_attempts to store the number of guesses the user has before they lose. I’m going to set it to 6, but you can change it if you want. Also define the variable called attempts to initialize before the start of your main loop. To create a variable in Python, you use the assignment operator = and give it a name and a value. For example, to create a variable called name and assign it the value "Matthew", you write name = "Matthew". Here’s the code for defining the words and the attempts:

# Define a list of words
words = ["tiger", "elephant", "giraffe", "zebra", "lion"]

# Define the maximum number of attempts
max_attempts = 6

# Initialize the number of attempts
attempts = 6

Picking a random word

Now we need to write a function that will pick a random word from the list and return it. A function is a block of code that performs a specific task and can be reused in other parts of the program. For our game, we’ll use the random.choice() function from the random module to pick a random word. We’ll also create a variable called word to store the chosen word. Here’s how you can pick a random word from the list using the random.choice() function:

# Define a function to pick a random word
def pick_word(words):
return random.choice(words)

# Pick a random word and store it in a variable
word = pick_word(words)

This function takes a list of words as a parameter and returns a random element from it. We then call the function and assign the returned value to a variable called word. This will be the secret word that the user has to guess.

Displaying the hangman

Now that we have the word, we also need a function that will display the hangman on the screen, depending on how many attempts the user has left. We’ll use a list of strings, each one representing a stage of the hangman. We’ll use triple quotes to create multi-line strings. We’ll also use the os.system() function to clear the screen before printing the hangman. Here’s the code:

# Define a function to display the hangman
def display_hangman(attempts):
# Define a list of hangman stages
stages = ["""
------
| |
| O
| /|\\
| / \\
|
------------
""",
"""
------
| |
| O
| /|\\
| /
|
------------
""",
"""
------
| |
| O
| /|\\
|
|
------------
""",
"""
------
| |
| O
| |
|
|
------------
""",
"""
------
| |
| O
|
|
|
------------
""",
"""
------
| |
|
|
|
|
------------
"""]

# Clear the screen
os.system("clear")

# Print the hangman stage based on the number of attempts left
print(stages[max_attempts - attempts])

Displaying the word

We also need a function that will display the word on the screen, with underscores for the letters that the user hasn’t guessed yet. We’ll use a list comprehension to create a list of underscores, and then join them with spaces using the str.join() method. We’ll also print the number of attempts left and the letters that the user has already guessed. Here’s the code:

# Define a function to display the word
def display_word(word, guessed_letters):
# Create a list of underscores for each letter in the word
blanks = ["_" if letter not in guessed_letters else letter for letter in word]

# Join the list with spaces and print it
print(" ".join(blanks))

# Print the number of attempts left
print(f"You have {attempts} attempts left.")

# Print the guessed letters
print(f"You have guessed these letters: {guessed_letters}")

This function takes the word and the guessed letters as parameters and prints the word with the guessed letters revealed and the rest hidden. It also prints the remaining attempts and the guessed letters for the user’s convenience.

Get the user’s input

Finally, we need a function that will get the user’s input and check if it’s a valid letter. We’ll use the input() function to get the user’s input, and then convert it to lowercase using the str.lower() method. We’ll also check if the input is a single letter, and if it’s not in the list of guessed letters. If the input is valid, we’ll return it. Otherwise, we’ll print an error message and ask for another input. Here’s the code:

# Define a function to get the user's input
def get_input(guessed_letters):
# Get the user's input and convert it to lowercase
guess = input("Guess a letter: ").lower()

# Check if the input is a single letter
if len(guess) != 1 or guess not in ascii_letters:
print("Invalid input. Please enter a single letter.")
return get_input(guessed_letters)

# Check if the input is not in the list of guessed letters
if guess in guessed_letters:
print("You have already guessed that letter. Try another one.")
return get_input(guessed_letters)

# Return the input if it's valid
return guess

This function takes the guessed letters as a parameter and returns the user’s input if it’s a valid letter. It uses recursion to ask for another input if the input is invalid or already guessed.

Writing the game’s main loop

Now we have all the functions we need to make our game. The last step is to write the main loop that will run the game. We’ll use a while loop that will keep running until the user runs out of attempts or guesses the word. Inside the loop, we’ll do the following:

  • Display the hangman and the word using the functions we defined earlier.
  • Get the user’s input using the function we defined earlier.
  • Add the input to the list of guessed letters.
  • Check if the input is in the word. If it is, print a message saying that the user guessed correctly. If it’s not, print a message saying that the user guessed wrong, and reduce the number of attempts by one.
  • Check if the user has guessed all the letters in the word. If they have, print a message saying that they won, and break the loop. If they haven’t, continue the loop.
  • Check if the user has no more attempts left. If they don’t, print a message saying that they lost, and reveal the word. Then break the loop. Here’s the code:
# Initialize the list of guessed letters
guessed_letters = ""

# Start the main loop
while True:
# Display the hangman and the word
display_hangman(attempts)
display_word(word, guessed_letters)

# Get the user's input
guess = get_input(guessed_letters)

# Add the input to the list of guessed letters
guessed_letters += guess

# Check if the input is in the word
if guess in word:
# Print a message saying that the user guessed correctly
print(f"Good guess! {guess} is in the word.")
else:
# Print a message saying that the user guessed wrong
print(f"Sorry, {guess} is not in the word.")

# Reduce the number of attempts by one
attempts -= 1

# Check if the user has guessed all the letters in the word
if all(letter in guessed_letters for letter in word):
# Print a message saying that the user won
print(f"Congratulations! You guessed the word: {word}")

# Break the loop
break

# Check if the user has no more attempts left
if attempts == 0:
# Print a message saying that the user lost
print(f"You ran out of attempts. You lost. The word was: {word}")

# Break the loop
break

Go play the game!

You’ve just used Python to build your hangman game. Now it’s time to see how it works and have some fun. Here’s how you can run and play the game from the command line:

  • Open Visual Studio Code and save your code as a file with the extension .py, such as hangman.py.
  • Open Terminal and navigate to the folder where you saved your file. You can use the cd command to change directories, and the ls command to list the files and folders in the current directory.
  • Type python3 hangman.py and press Enter to run your file. This will start the game and display the hangman and the word on the screen.
  • Follow the instructions on the screen and guess a letter by typing it and pressing Enter. If you guess correctly, the letter will show up on the word. If you guess wrong, you will lose one of your attempts and the hangman will get closer to being hanged.
  • Keep guessing until you either guess the word or run out of attempts. The game will tell you if you won or lost, and reveal the word at the end.

Here’s a screenshot of how it looks when you run it:

For an extra challenge

If you want to make your game more interesting, you can try adding some features, such as:

  • Adding more words to the list or using a different theme, such as movies, countries, or celebrities.
  • Adding hints or clues to help the user guess the word, such as the category, the definition, or the first letter.
  • Adding a scoring system or a timer to keep track of the user’s performance and reward them for guessing quickly or accurately.
  • Adding sound effects or graphics to make the game more immersive and appealing.

The possibilities are endless. You can use your creativity and imagination to make your game as awesome as you want.

That’s a wrap!

In this guide, you’ve learned the ropes of building a hangman game in Python, using the tools of the trade like Visual Studio Code and Terminal for Mac. You’ve wrangled with the fundamental concepts and features, such as variables, data types, functions, loops, conditions, and modules. You’ve also seen how to import modules, define functions, reel in user input, display the word and the hangman, and check the game logic. On top of all that, you know how to run and play the game from the command line, and how to add a few bells and whistles to make it more challenging. How’s that for a ride?

The complete Python code for this tutorial can be found on my GitHub repo at: https://github.com/kbrast/Pythonista/tree/main/hangman

For more info about building games in Python, check out these resources. Have fun and keep coding!

Click to connect with me on LinkedIn

--

--