【问题标题】:Why does my code ignore my if statement for my hangman game? (python)为什么我的代码会忽略我的刽子手游戏的 if 语句? (Python)
【发布时间】:2021-07-28 03:55:33
【问题描述】:

我刚刚对我在下面编写的代码有疑问。我只是想知道我用“if guess not in secret_word:”写的 if 语句。当我按照当前编写的方式运行它时,条件甚至不会运行或出现。但是,当我将它与上面写的 for 语句交换时,它运行得很好。我对编程有点陌生,我只是想知道是否有人可以帮助我解决这个问题。为什么这里的条件顺序很重要?

'''

import random
from words import words

secret_word = random.choice(words)
secret_letters = list(secret_word)
blanks = " _ " * len(secret_word)
already_guessed = []
lives = 10

print(blanks)


def valid_guess(): # function to make sure the letter guessed is valid (ie, not previously guessed)
    is_letter = True
    lives = 10

    while True:
        guess = (input("\nGuess a letter:"))

        if guess in already_guessed:
            print("You have already guessed this letter")
        elif len(guess) != 1:
            print("Please guess a single letter:")
            is_letter = False
        elif guess not in "abcdefghijklmnopqrstuvwxyz":
            print("Please guess a LETTER:")
            is_letter = False

        if is_letter:
            already_guessed.append(guess)

        for guess in secret_word:
            if guess in already_guessed:
                print(guess + " ", end = "")
            else:
                print(" - ", end = "")

        if guess not in secret_word:
            lives -= 1
            print(f"You lost a life! You only have {lives}/10 left!")


while True:
    valid_guess()

'''

【问题讨论】:

  • 您从用户输入中获得的guess 已被for guess in secret_word 覆盖。也许你想要if guess in secret_word,而不是for

标签: python syntax


【解决方案1】:

你可以试试这个:

if guess in secret_word:
       if guess in already_guessed:
            print(guess + " ", end = "")
       else:
            print(" - ", end = "")

 elif guess not in secret_word:
       lives -= 1
       print(f"You lost a life! You only have {lives}/10 left!")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 2018-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多