0% found this document useful (0 votes)
15 views2 pages

Code For Hangman

The document contains code for a Hangman game that selects a random word, displays guesses with placeholders for unknown letters, checks if the word is guessed, and runs the main game loop tracking attempts.

Uploaded by

faiezahmad562
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views2 pages

Code For Hangman

The document contains code for a Hangman game that selects a random word, displays guesses with placeholders for unknown letters, checks if the word is guessed, and runs the main game loop tracking attempts.

Uploaded by

faiezahmad562
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 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