Let’s play the Hangman game with Python

Valentina Alto
Aug 21, 2019 · 4 min read

Who has never played at least once the Hangman game? It was the perfect escape from a boring lesson and you only needed one paper and a pen. The idea is very simple: one player thinks about a word and the others have to guess, letter by letter, which is the word. The maximum number of wrong attempts depends on the way you decide to build your scaffold, however here we will set it equal to 10.

Every time your guessed letter is correct, the player who decided the word has to tell you the position of that letter, otherwise, the number of wrong attempts rises by 1 and the scaffold starts growing.

In this article, I’m going to build from scratch a Hangman game with Python, which will be the player who decides the word. For that purpose, I first downloaded from the module nltk.corpus a list of 236736 english words among which Python will decide.

import nltk
from nltk.corpus import words
word_list = words.words()

Then, I set some variables which will be used throughout the game. Those are:

  • guess: an empty list which will be filled with my guessed letters
  • secret: it is the secret word we want to guess
  • length_word= the number of characters of the secret word
  • abc= my alphabet
  • letter_storage= an empty list where all the guessed letters (both wrong and correct) will be appended.
import randomguess = []# lets randomize single word from the list
secret = random.choice(word_list)
length_word = len(secret)
abc = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []

Now I’m going to define three functions for my purpose:

  • greetings(): it will create a first contact with the user, asking him his name and whether he wants to play
def greetings():
print("Hello Mate!\n")
while True:
name = input("Please enter your name\n").strip()
if name == '':
print("You can't do that! No blank lines")
choice=input('Do you want to play Hangman?\n').lower()
if choice=='no' or choice=='n':
print("That's a shame! Have a nice day")
elif choice=='yes' or choice=='y':
print("Awesome! So let's start! If you want to exit,
just type 'bye'")

print("Please Answer only Yes or No")
  • structure(): it will display the structure of the secret word, replacing consonants with ‘-’ and vowels with ‘*’. Note that, since you are going to use those functions for many matches, at the very beginning of the function I emptied the list guess[], so that it will not contain the symbols of previous secret words.
import randomvowels=list(['a','e','i', 'o', 'u'])
def structure():
#let's remove the previous letter in our guess word
for character in secret:
if character in vowels:
guess.append('*') #if in that position there is a vowel
guess.append('-') #if in that position there is a
print("Ok, so the word you need to guess has {}
print("Be aware that you can enter only 1 letter from a-z\n\n")
  • guessing(): it is the function which will state whether our guessed letter is contained into the secret word. It asks us our guess, then it checks whether you want to quit the game (‘bye’), whether the input is a letter and whether that letter has already been picked (and hence stored into the letter_storage[]). Then, if the letter is in the secret word, it sets it into the right position in the list guess[], otherwise it tells us we were wrong and increases the number of wrong attempts by 1.
def guessing():
letter_storage.clear() #emptying the list
guess_taken = 1
while guess_taken < 10: guess_letter = input("Pick a letter\n").lower() if guess_letter=='bye':
elif not guess_letter in abc: #checking input
print("Enter a letter from a-z alphabet")
#checking if letter has been already used
elif guess_letter in letter_storage:
print("You have already guessed that letter!")
if guess_letter in secret:
print("You guessed correctly!")
for _i in range(length_word):
if secret[_i] == guess_letter:
guess[_i] = guess_letter
#updating the list by substituting - or * with the right guess
if not ('-' and '*') in guess:
print("You won!")
print("The letter is not in the word. Try
guess_taken += 1
if guess_taken == 10:
print(" Sorry Mate, You lost :<! The secret word
was {}".format(secret))

Now we can run our three functions at one time like so:

if __name__ == "__main__":

Nice! Now let’s play:

I have to admit it, I cheated so badly before playing (I had a glimpse at the secret word, shame on me) and I’m glad I did that, since I had no idea of what a mormaor was. For those who are curious:

“ A mormaor is a Scottish nobleman serving as a high steward of a province”

Armed with this new knowledge, let’s check that my escape system runs:

And finally, let’s check what happens if we take more than 10 attempts:

Great! Now you can have your fun against Python while playing the Hangman game. Hoping you enjoyed the reading!

The Startup

Get smarter at building your thing. Join The Startup’s +787K followers.

Sign up for Top 10 Stories

By The Startup

Get smarter at building your thing. Subscribe to receive The Startup's top 10 most read stories — delivered straight into your inbox, once a week. Take a look.

By signing up, you will create a Medium account if you don’t already have one. Review our Privacy Policy for more information about our privacy practices.

Check your inbox
Medium sent you an email at to complete your subscription.

Valentina Alto

Written by

Cloud Specialist at @Microsoft | MSc in Data Science | Machine Learning, Statistics and Running enthusiast

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Valentina Alto

Written by

Cloud Specialist at @Microsoft | MSc in Data Science | Machine Learning, Statistics and Running enthusiast

The Startup

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +787K followers.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store