问题
I am trying to design a hungman game using simple while loop and if else statement.
Rules of the game:
1.Random word is selected from a list of words
2.User is informed when the word is selected and asked to provide his/ her first guess
3.If the user's guess is correct, the letter is console and inform the user how many letters left
The user will get only 5 lives to play the game.
1.import random 2.import string 3.def hungman(): 4.words = ["dog", "monkey", "key", "money", "honey"] 5.used_letters = [] 6.word = words[random.randrange(len(words))] 7.lives=5 8.while len(word) > 0 and lives > 0: 9.guess = input("Please guess the letter: ") 10.if 'guess' in word: 11.print(guess, " is a correct guess") 12.used_letters.appened(guess) 13.if used_letters.len == word.len: 14.print("Congratulation, You have guessed the correct letter: ",word) 15.else: 16.remaining_letters = word.len - used_letters.len 17.print("You have", remaining_letters, "left") 18.else: 19.lives = lives - 1 20.if lives == 0: 21.print("Sorry! you don't have more lives to continue the game") 22.print("Correct word is: ", word) 23.break 24.else: 25.print("You have", lives , " left") 26.hungman()
The program should ask for the user input which will store in guess
variable. If the letter given by the user is one of the letters of word string then the code prompts that the given input is correct and append the letter in the used_letters list. Else it shows the length of the remaining letters for wrong user input. Additionally, if the user fails to guess the letter correctly he or she will lose 1 life as well.
However, as per my code after the while loop in line number 8 the control goes to line no. 18 although I provided correct letter as user input. Line 10 to 17 totally discarded. I could not find the reason of this nature.
Please help me in this regard.
Thank you
回答1:
You have a couple of issues in your code. The one you mentioned is because of quotation marks in line 10. Should be
if guess in word:
in line 12 you have a typo
used_letters.append(guess)
to get the length of a list you should use function len(), e.g.
if len(used_letters) == len(word)
And finally you have an issue with exiting the loop in case of the correct answer. You should use
while len(word) > len(used_letters) and lives > 0:
来源:https://stackoverflow.com/questions/65798644/simple-hangman-game-using-while-and-if-else-loop-does-not-iterate-correctly