I wore code for hangman game, bur for some reason while loop continues and I need to force the programme to stop. please look into the code and explain me what is the probleme in it. Thanks
import random
word_list = ['apple', 'banana', 'mango', 'kiwi', 'grapes']
num_lives = 5
print(word_list)
choice = random.choice(word_list)
print(choice)
display=[]
for i in range (len(choice)):
display = '_'
print(display)
game_over=False
while not game_over:
gussed_letter=input("Gusse a letter").lower()
for position in range(len(choice)):
letter = choice[position]
if letter == gussed_letter:
display[position] = gussed_letter
print(display)
if gussed_letter not in choice:
num_lives -=1
if num_lives == 0:
game_over = True
print('You died, Game over!')
if '_' not in display:
game_over = True
print('You have won the game')
I tried VS code for python hangman game, game is not stopping and loop continues.
CodePudding user response:
if gussed_letter not in choice:
num_lives -=1
if num_lives == 0:
game_over = True
print('You died, Game over!')
if '_' not in display:
game_over = True
print('You have won the game')```
It does not work because you do not put them in the while loop.
CodePudding user response:
here,your guessed_letter not in choice is outside while loop bring it inside loop import random
word_list = ['apple', 'banana', 'mango', 'kiwi', 'grapes'] num_lives = 5 print(word_list)
choice = random.choice(word_list) print(choice)
display = []
for i in range(len(choice)): display = '_'
print(display)
game_over = False
while not game_over: guessed_letter = input("Guess a letter: ").lower()
for position in range(len(choice)):
letter = choice[position]
if letter == guessed_letter:
display[position] = guessed_letter
print(display)
if guessed_letter not in choice:
num_lives -= 1
if num_lives == 0:
game_over = True
print('You died, Game over!')
if '_' not in display:
game_over = True
print('You have won the game')