Python Hangman Game: Code, Play, and Learn

Learn how to create a simple Hangman game in Python. This step-by-step guide covers random word selection from a predefined list, displaying the current state of the guessed word, and handling user inputs to guess letters. Understand the main game logic, including updating the game state based on correct or incorrect guesses, and see how the game progresses until the player wins or loses.

import random

# List of possible words
words = ["python", "java", "kotlin", "javascript"]

# Function to choose a random word from the list
def choose_word():
    return random.choice(words)

# Function to display the current state of the guessed word
def display_word(word, guessed_letters):
    display = ''
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += '_'
    return display

# Main function to play the game
def play_hangman():
    word = choose_word()
    guessed_letters = set()
    tries = 6

    print("Welcome to Hangman!")
    while tries > 0:
        print("\n" + display_word(word, guessed_letters))
        guess = input("Guess a letter: ").lower()

        if guess in guessed_letters:
            print("You already guessed that letter.")
        elif guess in word:
            guessed_letters.add(guess)
            print(f"Good guess! {guess} is in the word.")
        else:
            tries -= 1
            print(f"Wrong guess! {guess} is not in the word. {tries} tries left.")

        if set(word) == guessed_letters:
            print(f"Congratulations! You guessed the word: {word}")
            break
    else:
        print(f"Game over! The word was: {word}")

# Start the game
play_hangman()

Explanation:

  1. Importing random module: Used to choose a random word from the list.
  2. List of words: words contains the possible words for the game.
  3. Function choose_word(): Selects a random word from the list.
  4. Function display_word(): Returns the current state of the word, showing guessed letters and underscores for remaining letters.
  5. Function play_hangman(): Main game logic:
    • Chooses a random word.
    • Initializes guessed letters set and remaining tries.
    • Continuously prompts the player to guess a letter until the word is guessed or tries run out.
    • Checks if the guessed letter is in the word and updates the game state accordingly.
  6. Starting the game: Calls play_hangman() to begin the game.