Code For Hangman

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

import random

def select_word():

"""Returns a randomly selected word from a predefined list."""

word_list = ["apple", "banana", "orange", "grape", "pineapple"]

return random.choice(word_list)

def display_word(word, guessed_letters):

"""Displays the word with correctly guessed letters and placeholders for the rest."""

displayed_word = ""

for letter in word:

if letter in guessed_letters:

displayed_word += letter

else:

displayed_word += "_"

return displayed_word

def is_word_guessed(word, guessed_letters):

"""Checks if all letters of the word have been guessed."""

for letter in word:

if letter not in guessed_letters:

return False

return True

def hangman():

"""Main function to play the Hangman game."""

print("Welcome to Hangman!")

secret_word = select_word()

guessed_letters = []
attempts_left = 6

while attempts_left > 0:

print("\nAttempts left:", attempts_left)

displayed_word = display_word(secret_word, guessed_letters)

print("Word:", displayed_word)

guess = input("Guess a letter: ").lower()

if guess in guessed_letters:

print("You already guessed that letter. Try again.")

continue

elif len(guess) != 1 or not guess.isalpha():

print("Invalid input. Please enter a single letter.")

else:

guessed_letters.append(guess)

if guess not in secret_word:

print("Incorrect guess!")

attempts_left -= 1

if is_word_guessed(secret_word, guessed_letters):

print("\nCongratulations! You guessed the word:", secret_word)

break

else:

print("\nSorry, you ran out of attempts. The word was:", secret_word)

if __name__ == "__main__":

hangman()

```

You might also like