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()
random module: Used to choose a random word from the list.words contains the possible words for the game.choose_word(): Selects a random word from the list.display_word(): Returns the current state of the word, showing guessed letters and underscores for remaining letters.play_hangman(): Main game logic:
play_hangman() to begin the game.