In this post we will be recreating the hangman game in Python, to help us achieve this we will use the random module. The random module enables the generation of random numbers and allows us to pick random items from sequences like lists or tuple.
See the snippet of Python code below where we utilise the random module to create the hangman game. In the code we define a list of words and carry out a random selection for the game. The user is given seven turns to guess the entire word before the game comes to an end. Our turns count is subtracted by one each time an incorrect letter is given. Any correct letters are presented to the user as well as their position within the word.
import random
def hangman_game():
words = ["avenue", "awkward", "bandwagon", "numbskull"]
word = random.choice(words)
guessed = set()
turns = 7
while turns > 0:
for letter in word:
if letter in guessed:
print(letter, end=" ")
else:
print("_", end=" ")
print("")
guess = input("Enter a letter: ")
guessed.add(guess)
if guess not in word:
turns -= 1
print(f"Wrong! {turns} turns left")
if turns == 0:
print("Game over!")
print(f"The word was {word}")
return
if all(letter in guessed for letter in word):
print("Congratulations, you won!")
return
hangman_game()
See an example game below.
_ _ _ _ _ _ _ _ _
Enter a letter: a
_ a _ _ _ a _ _ _
Enter a letter: c
Wrong! 6 turns left
_ a _ _ _ a _ _ _
Enter a letter: b
b a _ _ _ a _ _ _
Enter a letter: n
b a n _ _ a _ _ n
Enter a letter: z
Wrong! 5 turns left
b a n _ _ a _ _ n
Enter a letter: d
b a n d _ a _ _ n
Enter a letter: w
b a n d w a _ _ n
Enter a letter: g
b a n d w a g _ n
Enter a letter: i
Wrong! 4 turns left
b a n d w a g _ n
Enter a letter: o
Congratulations, you won!
>>>
Take a look at some of our other content around the Python programming language by clicking here.