Hangman game is just a word guessing game by guessing the character of the word. In this game, there is a list of words present, out of which our interpreter will choose 1 random word.
The user first has to input their names and then, will be asked to guess any alphabet. If the random word contains that alphabet, it will be shown as the output(with correct placement) else the program will ask you to guess another alphabet. Users will be given 12 turns(can be changed accordingly) to guess the complete word.
# library that we use in order to choose
# on random words from a list of words
import random
# Here the user is asked to enter the name first
name = input("Enter your name: ")
print("All the best", name)
words = [
"website",
"hangman",
"rainbow",
"computer",
"science",
"programming",
"python",
"mathematics",
"player",
"apple",
"reverse",
"water",
"binod",
"codesnail",
]
# Function will choose one random
# word from this list of words
word = random.choice(words)
print("\nGuess the characters")
guesses = ""
# any number of turns can be used here
turns = 12
while turns > 0:
# counts the number of times a user fails
failed = 0
# all characters from the input
# word taking one at a time.
for char in word:
if char in guesses:
print(char, end="")
else:
print("_", end="")
# for every failure 1 will be
# incremented in failure
failed += 1
if failed == 0:
# user will win the game if failure is 0
# and 'You Win' will be given as output
print("\n\nYou Win")
# this print the correct word
print("\nThe word is: ", word)
break
# if user has input the wrong alphabet then
# it will ask user to enter another alphabet
guess = input("\n\nguess the character: ")
# every input character will be stored in guesses
guesses += guess
# check input with the character in word
if guess not in word:
turns -= 1
# if the character doesnβt match the word
# then βWrongβ will be given as output
print("\nWrong")
# this will print the number of
# turns left for the user
print("\nYou have", +turns, "more guesses")
if turns == 0:
print("\n\nYou lose")
original: Hangman Game in Python
More python projects π
Top comments (4)
Cool I started learning Python a few days ago this syntax does not look as weird to me now. π
Great β₯οΈ
thank youuuuuu
Welcome :)