I'm making a simple hangman program using while-loops. The program that I've written works, but I don't know how to make it stop once the user has guessed the correct letters.
Here is what I have so far:
word = input("What's the secret word? ")
lives = int(input("Amount of lives? "))
while True:
guess = input("Guess a letter: ")
if guess in word:
print("Correct, the letter is in the secret word.")
else:
lives -= 1
print(f"The letter {guess} is not in the secret word.")
if lives > 0:
print(f"You have {lives} lives left, try again.")
else:
print("You have no lives left.")
break
CodePudding user response:
The simplest way I see is to add some counter of correctly guessed letters, so you can reason when the word itself is guessed correctly.
guessed_so_far = 0
already_guessed = []
while True:
guess = input("Guess a letter: ")
if guess in word and guess not in already_guessed:
print("Correct, the letter is in the secret word.")
guessed_so_far = 1
already_guessed.append(guess)
if guessed_so_far == len(set(word)):
break
As Joshua correctly suggested, you have to compare with len(set(word))
CodePudding user response:
Your guess = input(...)
code has a subtle bug: what if the user inputs a len(guess) > 1
string? Ignoring that possibility for a moment:
word = input("What's the secret word? ")
letters = set(word)
...
# if the guess (assumed single character) is in the set of letters
if guess in letters:
print("Correct, the letter is in the secret word.")
# reduce the set of letters remaining by the current guess
letters = letters - set(guess)
# if there aren't any letters left to guess
if len(letters) == 0:
print("Congrats! You won!")
break