Untitled
unknown
plain_text
3 years ago
2.5 kB
5
Indexable
import random
# list of words to choose from
words = ["apple", "banana", "cherry", "durian", "elderberry", "fig", "grape", "honeydew", "kiwi", "lemon"]
# select a random word from the list
word = random.choice(words)
# create a list of underscores to represent the unknown letters in the word
guesses = ["_" for letter in word]
# keep track of the number of incorrect guesses
num_guesses = 0
# loop until the player guesses the word or runs out of guesses
while num_guesses < 6 and "_" in guesses:
# ask the player to guess a letter
guess = input("Guess a letter: ").lower()
# check if the guess is in the word
if guess in word:
# replace the corresponding underscore with the guessed letter
for i, letter in enumerate(word):
if letter == guess:
guesses[i] = guess
print(" ".join(guesses))
else:
# increment the number of incorrect guesses
num_guesses += 1
print("Incorrect. You have", 6 - num_guesses, "guesses left.")
# display the hangman figure
if num_guesses == 1:
print(" _______")
print(" |/ |")
print(" | (_)")
print(" |")
print(" |")
print(" |")
print("_|_")
elif num_guesses == 2:
print(" _______")
print(" |/ |")
print(" | (_)")
print(" | |")
print(" |")
print(" |")
print("_|_")
elif num_guesses == 3:
print(" _______")
print(" |/ |")
print(" | (_)")
print(" | \\|")
print(" |")
print(" |")
print("_|_")
elif num_guesses == 4:
print(" _______")
print(" |/ |")
print(" | (_)")
print(" | \\|/")
print(" |")
print(" |")
print("_|_")
elif num_guesses == 5:
print(" _______")
print(" |/ |")
print(" | (_)")
print(" | \\|/")
print(" | |")
print(" |")
print("_|_")
elif num_guesses == 6:
print(" _______")
print(" |/ |")
print(" | (_)")
print(" | \\|/")
print(" | |")
print(" | / ")
print("_|_")
# check if the player won or lost
if num_guesses < 6:
print("Congratulations, you guessed the word!")
else:
print("Sorry, you ran out of guesses. The word was", word)
Editor is loading...