Hangman Game in Python

Hangman Game in Python

Let's create a simple text-based Hangman game in Python.

The basic rules:

  1. Player is shown the word they have to guess with its letters replaced by underscores (e.g., '_ _ _ _ _' for "apple").
  2. Player guesses one letter at a time.
  3. The game continues until the player has made 6 incorrect guesses or has guessed the word.

Here's a simple implementation:

import random def hangman(): word_list = ["python", "java", "javascript", "ruby", "html", "css", "django", "flask"] random_word = random.choice(word_list) guessed_word = ["_"] * len(random_word) guessed_letters = [] tries = 6 print("Let's play Hangman!") print(' '.join(guessed_word)) while tries > 0 and '_' in guessed_word: guess = input("Guess a letter: ").lower() if len(guess) != 1 or not guess.isalpha(): print("Please enter only one letter!") continue if guess in guessed_letters: print("You already guessed that letter!") continue guessed_letters.append(guess) if guess in random_word: for idx, letter in enumerate(random_word): if letter == guess: guessed_word[idx] = guess else: tries -= 1 print(f"Wrong guess. {tries} tries left!") print(' '.join(guessed_word)) if '_' not in guessed_word: print("Congratulations! You've guessed the word!") else: print(f"You're out of tries! The word was '{random_word}'.") hangman() 

This is a simple implementation. There are many ways to enhance the game:

  1. Displaying a hangman figure ASCII art for each incorrect guess.
  2. Allowing the player to guess the entire word, not just letters.
  3. Expanding the word list or sourcing it from a file or API.
  4. Adding more feedback or making the UI more interactive (using libraries like curses for console or using a GUI library).

Feel free to explore and expand upon this implementation!


More Tags

forward path recordset page-break-inside serverxmlhttp angular-filters azure-application-insights math system.drawing angular-router-guards

More Programming Guides

Other Guides

More Programming Examples