Code Explanation of Hangman Game
Code Explanation of Hangman Game
‘import random`: This line imports the `random` module, which allows us to generate random
numbers and choose random elements from a list.
2. ‘def select_word():`: This line defines a function named `select_word`. Functions are blocks of
reusable code. This function doesn't take any arguments and returns a randomly selected word from a
predefined list.
3. `"""Returns a randomly selected word from a predefined list."""`: This is a documentation string
(docstring) that describes what the `select_word` function does. It's a good practice to include
docstrings to explain the purpose of functions.
4. `word_list = ["apple", "banana", "orange", "grape", "pineapple"]`: This line defines a list called
`word_list` containing several words that could be chosen for the game.
5. `return random.choice(word_list)`: This line uses the `random.choice()` function to select a random
word from the `word_list` and returns it.
6. `def display_word(word, guessed_letters):`: This line defines a function named `display_word` that
takes two arguments: `word`, which is the secret word to be guessed, and `guessed_letters`, which is a
list of letters that the player has guessed so far.
7. `"""Displays the word with correctly guessed letters and placeholders for the rest."""`: This is a
docstring explaining the purpose of the `display_word` function.
8. `displayed_word = ""`: This line initializes an empty string called `displayed_word` to hold the word as
it's being displayed to the player.
9. `for letter in word:`: This line starts a loop that iterates over each letter in the `word`.
10. `if letter in guessed_letters:`: This line checks if the current letter is in the list of `guessed_letters`.
11. `displayed_word += letter`: If the letter has been guessed, it adds the letter to the `displayed_word`.
12. `else:`: If the letter hasn't been guessed, this line executes.
13. `displayed_word += "_"`: It adds an underscore `_` (placeholder) to the `displayed_word` instead of
the letter.
14. `return displayed_word`: After looping through all the letters in the word, this line returns the
`displayed_word` string, which shows the secret word with correctly guessed letters revealed and
placeholders for the rest.
16. `"""Checks if all letters of the word have been guessed."""`: This is a docstring explaining the purpose
of the `is_word_guessed` function.
17. `for letter in word:`: This line starts a loop that iterates over each letter in the `word`.
18. `if letter not in guessed_letters:`: This line checks if the current letter is not in the list of
`guessed_letters`.
19. `return False`: If there's at least one letter in the word that hasn't been guessed, the function returns
`False`.
20. `return True`: If all the letters in the word have been guessed, the function returns `True`.
21. `def hangman():`: This line defines the main function of the game, named `hangman`.
22. `"""Main function to play the Hangman game."""`: This is a docstring explaining the purpose of the
`hangman` function.
23. `print("Welcome to Hangman!")`: This line prints a welcome message to the player.
24. `secret_word = select_word()`: This line calls the `select_word` function to choose a secret word for
the game and assigns it to the variable `secret_word`.
25. `guessed_letters = []`: This line initializes an empty list called `guessed_letters` to keep track of the
letters the player has guessed.
26. `attempts_left = 6`: This line sets the variable `attempts_left` to 6, indicating how many incorrect
guesses the player is allowed before losing the game.
27. `while attempts_left > 0:`: This line starts a while loop that continues as long as there are attempts
left.
28. `print("\nAttempts left:", attempts_left)`: This line prints the number of attempts left to the player.
30. `print("Word:", displayed_word)`: This line prints the current state of the word to the player.
31. `guess = input("Guess a letter: ").lower()`: This line prompts the player to guess a letter and converts
the input to lowercase.
32. `if guess in guessed_letters:`: This line checks if the guessed letter is already in the list of
`guessed_letters`.
33. `print("You already guessed that letter. Try again.")`: If the letter has already been guessed, this line
prints a message to inform the player.
34. `continue`: This line continues to the next iteration of the loop without executing the rest of the
code if the player has already guessed the letter.
35. `elif len(guess) != 1 or not guess.isalpha():`: This line checks if the input is not a single letter or if it
contains characters other than letters.
36. `print("Invalid input. Please enter a single letter.")`: If the input is invalid, this line prints a message to
inform the player.
37. `guessed_letters.append(guess)`: This line adds the guessed letter to the list of `guessed_letters`.
38. `if guess not in secret_word:`: This line checks if the guessed letter is not in the secret word.
39. `print("Incorrect guess!")`: If the guessed letter is not in the secret word, this line prints a message to
inform the player.
40. `attempts_left -= 1`: This line decrements the number of attempts left.
41. `if is_word_guessed(secret_word, guessed_letters):`: This line checks if all the letters of the secret
word have been guessed.
42. `print("\nCongratulations! You guessed the word:", secret_word)`: If all the letters have been
guessed, this line prints a congratulatory message to inform the player that they have won the game and
reveals the secret word.
43. `break`: This line exits the loop if the player has guessed the word correctly.
44. `else:`: If the player hasn't guessed the word correctly and there are still attempts left, this line
executes.
45. `print("\nSorry, you ran out of attempts. The word was:", secret_word)`: If the player runs out of
attempts without guessing the word correctly, this line prints a message to inform the player that they
have lost the game and reveals the secret word.
46. `if __name__ == "__main__":`: This line checks if the script is being run directly (not imported as a
module).
47. `