Back to: Python Programming
0
This is an exercise do help us practice using functions in Python. We’ll start by breaking the program into smaller sections and work on them one at a time.
We’ll need a set of words and some functions: display_man(wrong_guesses), display_hint(hint) and display_answer(answer).
We’ll use ASCII art to display the man, once we get 6 incorrect guesses, he’ll be fully visible and we lose the game. Read through this code and ensure you fully understand what each function does and how it is working

Ensure you understand how this code works:
# Hangman in Python
import random
hangman_art = {0: (" ",
" ",
" "),
1: (" o ",
" ",
" "),
2: (" o ",
" | ",
" "),
3: (" o ",
"/| ",
" "),
4: (" o ",
"/|\\",
" "),
5: (" o ",
"/|\\",
"/ "),
6: (" o ",
"/|\\",
"/ \\")}
words = ("aardvark", "alligator", "alpaca", "ant", "anteater", "antelope", "ape", "armadillo", "baboon", "badger", "bat", "bear", "beaver", "bee", "bison", "boar", "buffalo", "butterfly", "camel", "capybara", "caribou", "cat", "caterpillar", "cattle", "chamois", "cheetah", "chicken", "chimpanzee", "chinchilla", "chough", "clam", "cobra", "cockroach", "cod", "coyote", "crab", "crane", "crocodile", "crow", "curlew", "deer", "dinosaur", "dog", "dogfish", "dolphin", "donkey", "dormouse", "dotterel", "dove", "dragonfly", "duck", "dugong", "dunlin", "eagle", "echidna", "eel", "eland", "elephant", "elk", "emu", "falcon", "ferret", "finch", "fish", "flamingo", "fly", "fox", "frog", "gaur", "gazelle", "gerbil", "giraffe", "gnat", "gnu", "goat", "goldfinch", "goldfish", "goose", "gorilla", "goshawk", "grasshopper", "grouse", "guanaco", "gull", "hamster", "hare", "hawk", "hedgehog", "heron", "herring", "hippopotamus", "hornet", "horse", "human", "hummingbird", "hyena", "ibex", "ibis", "jackal", "jaguar", "jay", "jellyfish", "kangaroo", "kingfisher", "koala", "kookabura", "kouprey", "kudu", "lapwing", "lark", "lemur", "leopard", "lion", "llama", "lobster", "locust", "loris", "louse", "lyrebird", "magpie", "mallard", "manatee", "mandrill", "mantis", "marten", "meerkat", "mink", "mole", "mongoose", "monkey", "moose", "mosquito", "mouse", "mule", "narwhal", "newt", "nightingale", "octopus", "okapi", "opossum", "oryx", "ostrich", "otter", "owl", "ox", "oyster", "panda", "panther", "parrot", "partridge", "peafowl", "pelican", "penguin", "pheasant", "pig", "pigeon", "polar-bear", "pony", "porcupine", "porpoise", "quail", "quelea", "quetzal", "rabbit", "raccoon", "rail", "ram", "rat", "raven", "red-deer", "red-panda", "reindeer", "rhinoceros", "rook", "salamander", "salmon", "sand-dollar", "sandpiper", "sardine", "scorpion", "seahorse", "seal", "shark", "sheep", "shrew", "skunk", "snail", "snake", "sparrow", "spider", "spoonbill", "squid", "squirrel", "starling", "stingray", "stoat", "stork", "swallow", "swan", "tapir", "tarsier", "termite", "tiger", "toad", "trout", "turkey", "turtle", "viper", "vulture", "wallaby", "walrus", "wasp", "weasel", "whale", "wildcat", "wolf", "wolverine", "wombat", "woodcock", "woodpecker", "worm", "wren", "yak", "zebra")
def display_man(wrong_guesses):
print("**********")
for line in hangman_art[wrong_guesses]:
print(line)
print("**********")
def display_hint(hint):
print(" ".join(hint))
def display_answer(answer):
print(" ".join(answer))
def main():
answer = random.choice(words)
hint = ["_"] * len(answer)
wrong_guesses = 0
guessed_letters = set()
is_running = True
while is_running:
display_man(wrong_guesses)
display_hint(hint)
guess = input("Enter a letter: ").lower()
if len(guess) != 1 or not guess.isalpha():
print("Invalid input")
continue
if guess in guessed_letters:
print(f"{guess} is already guessed")
continue
guessed_letters.add(guess)
if guess in answer:
for i in range(len(answer)):
if answer[i] == guess:
hint[i] = guess
else:
wrong_guesses += 1
if "_" not in hint:
display_man(wrong_guesses)
display_answer(answer)
print("YOU WIN!")
is_running = False
elif wrong_guesses >= len(hangman_art) - 1:
display_man(wrong_guesses)
display_answer(answer)
print("YOU LOSE!")
is_running = False
if __name__ == "__main__":
main()