代码之家  ›  专栏  ›  技术社区  ›  M. de Brock

为什么我的if语句在使用“and not”时返回false?[副本]

  •  0
  • M. de Brock  · 技术社区  · 1 年前

    我正试图用python制作一个刽子手游戏进行练习(我对编码很陌生,也是python的新手)当我试图检查一个“chosenLetter”是否在“randomWord”中,而不是在“correctLetters Used”中时,它只是决定了它 在那里,尽管它不是。当我第一次循环while循环时,它确实按预期工作,但一旦'correctLettersUsed'中有一个字母并再次循环,它就不会工作了。

    #get random word from list
    randomWord = wordList[random.randint(0, len(wordList))]
    
    #counters and correct letters used
    winAmount = len(randomWord) -1
    correctLettersUsed = []
    pointCounter = 0
    wrongGuesses = 0
    
    #loops until win conditions are met
    while len(correctLettersUsed) != winAmount:
    
        #print for testing
        print(randomWord)
    
        chosenLetter = input("Pick a letter: ")
    
        #checks if the chosen letter is in the random word and not in the used letters
        if chosenLetter in randomWord and not correctLettersUsed:
            pointCounter += 1
            print("Correct!")
            correctLettersUsed.append(chosenLetter)
            print("Correct letters: " + str(correctLettersUsed))
        else:
            wrongGuesses += 1
            print("Incorrect. " + "You have " + str(6 - wrongGuesses) + " guesses left.")
    

    我希望if声明是真的。我已尝试完全删除“使用过且不正确的信件”,然后它按预期工作。然而,你可以一遍又一遍地使用同一个字母来获胜。我能想到的只是“and not”只是检查“correctLettersUsed”中是否有任何内容,如果是这样,那将是真的,if语句将返回false,我不确定如何修复它。我也尝试过使用vscode调试工具,但我真的无法弄清楚。

    4 回复  |  直到 1 年前
        1
  •  2
  •   Cory Kramer    1 年前

    逻辑应该是

    if chosenLetter in randomWord and chosenLetter not in correctLettersUsed:
    

    否则,它被解释为

    if (chosenLetter in randomWord) and (not correctLettersUsed):
    

    其中任何真实(即非空)列表的计算结果为 True

        2
  •  0
  •   Bindestrich    1 年前

    编译器无法猜测and not短语也与randomWord的内容有关。正确的方法是

    if chosenLetter in randomWord and not correctLettersUsed  in randomWord :
    

    correctLetters Used是一个列表,当列表不为空时,列表为true。

    因此,只有当正确的Letters Used列表为空并且chosenLetter包含在randomWord列表中时,您的原始陈述才是正确的

        3
  •  0
  •   OneCricketeer Gabriele Mariotti    1 年前

    not correctLettersUsed 将始终返回true,因为 correctLettersUsed 这是一个列表。

    你想让它说 chosenLetter not in correctLettersUsed

        4
  •  0
  •   Gerardo    1 年前

    if语句应该这样写,以测试这两种情况:

    if (chosenLetter in randomWord) and (chosenLetter not in correctLettersUsed):
    

    目前,您的声明正在检查chosenLetter是否为randomWord格式,以及correctLetters Used是否有值。您没有检查chosenLetter是否正确。

    希望这能有所帮助!