import random
# List of words for the game
word_list = ["python", "programming", "hangman", "computer", "hello"]
def choose_word(word_list):
return random.choice(word_list)
# chooses a random word for the game
def display_word(word, guesses):
display = ""
for letter in word:
if letter in guesses:
display += letter
else:
display += "_"
return display
# prints the blank word
def hangman():
word_to_guess = choose_word(word_list)
guessed_letters = []
attempts = 6
print("Welcome to Hangman!")
print(display_word(word_to_guess, guessed_letters))
while attempts > 0:
guess = input("Guess a letter: ").lower()
if len(guess) == 1 and guess.isalpha():
if guess in guessed_letters:
print("You've already guessed that letter!")
# if letter is repeated, print you've already gussed that
elif guess in word_to_guess:
guessed_letters.append(guess)
print("Good guess!")
print(display_word(word_to_guess, guessed_letters))
else:
guessed_letters.append(guess)
attempts -= 1
print("Wrong guess! You have {} attempts left.".format(attempts))
print(display_word(word_to_guess, guessed_letters))
#if the guess is wrong, then...etc.
else:
print("Please enter a valid single letter.")
# if no letter is typed
if "_" not in display_word(word_to_guess, guessed_letters):
print("Congratulations! You've guessed the word: {}".format(word_to_guess))
break
if attempts == 0:
print("Game over! The word was: {}".format(word_to_guess))
if __name__ == "__main__":
hangman()
Welcome to Hangman!
_________
Guess a letter: a
Wrong guess! You have 5 attempts left.
_________
Guess a letter: e
Good guess!
_e_e___e_
Guess a letter: t
Wrong guess! You have 4 attempts left.
_e_e___e_
Guess a letter: s
Wrong guess! You have 3 attempts left.
_e_e___e_
Guess a letter: n
Wrong guess! You have 2 attempts left.
_e_e___e_
Guess a letter: m
Wrong guess! You have 1 attempts left.
_e_e___e_
Guess a letter: i
Wrong guess! You have 0 attempts left.
_e_e___e_
Game over! The word was: developer