How to Code the Hangman Game in Python: Easy to Follow [Step-by-Step]

Claudio Sabato
11 min readMar 4, 2022

In this tutorial we will create the hangman game in Python. We will follow a step-by-step process and gradually build it.

To code the hangman game in Python you have to use the input() function to ask the user to guess a letter. Then you keep track of the maximum number of attempts allowed and if that’s reached before guessing the full word the user loses. To print the hangman stages you can use multi-line strings.

We will start by writing the code to guess a single letter…

Once this is done we will repeat this code over and over using a Python while loop.

Are you ready? :)

Pick a Random Word for the Hangman in Python

Let’s start working on our hangman game by creating a Python function that returns a random word for our user to guess.

Import the random module and define a list of strings that contains 5 words.

import randomwords = ["tiger", "tree", "underground", "giraffe", "chair"]

Then add a function called select_word() that randomly selects one word from the list using the function random.choice().

The random.choice() function returns a random element from a sequence.

def select_word(words):
return random.choice(words)

Call the function and test the Python program several times to make sure you get back random words…

print(select_word(words))

Here is the output:

$ python hangman.py
tree
$ python hangman.py
underground
$ python hangman.py
chair

The function works fine.

Which Variables Do We Need for the Hangman Game?

For our hangman game we will need the following variables:

  • remaining_attempts: this is an integer and represents the number of remaining attempts to guess the “secret” word. This value will be initially set to 6 (head + body + arms + legs).
  • guessed_letters: a string that contains all the letters guessed by the user that…
Claudio Sabato

I’m a Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!