3.1k views
0 votes
Can you write me a hangman game in python 1?

1 Answer

3 votes

import random

def hangman():

words = ['apple', 'banana', 'orange', 'grape', 'strawberry'] # List of words to guess from

word = random.choice(words) # Select a random word

guesses = [] # List to store guessed letters

attempts = 6 # Number of attempts allowed

while True:

# Display the current state of the word

display_word = ''

for letter in word:

if letter in guesses:

display_word += letter

else:

display_word += '_'

print("Word:", display_word)

if display_word == word:

print("Congratulations! You guessed the word correctly!")

break

# Get user input

guess = input("Enter a letter: ").lower()

if guess in guesses:

print("You already guessed that letter.")

elif guess.isalpha() and len(guess) == 1:

guesses.append(guess)

if guess in word:

print("Correct guess!")

else:

attempts -= 1

print("Wrong guess!")

print("Attempts remaining:", attempts)

if attempts == 0:

print("Game over! You ran out of attempts.")

print("The word was:", word)

break

else:

print("Invalid input. Please enter a single letter.")

hangman()

In this game, a random word is selected from a list, and the player has to guess the letters of the word within a certain number of attempts. The player enters a letter, and the program checks if it is a correct guess or not. The game continues until the word is guessed correctly or the player runs out of attempts.

Feel free to customize and enhance the code as per your requirements.

User AnthonyY
by
8.1k points