【问题标题】:How to properly use the 'not()' operator in Python如何在 Python 中正确使用“not()”运算符
【发布时间】:2021-09-30 07:26:21
【问题描述】:

(再次)学习如何用 Python 编写代码,我正在为此做这个简单的猜词游戏。代码(写在下面)来自我一直关注的 YouTube 视频(freeCodeCamp 的 Learn Python - Full Course for Beginners [Tutorial])。

我不明白not(guesses_complete) 在这个代码中的逻辑意义。

根据我的理解,代码暗示while循环执行并继续,只要玩家的猜测不是秘密单词并且guesses_complete的布尔值为True(因为guesses_complete的初始值为False,所以not() 表示该值必须为 True 才能执行)。

但是guesses_complete的初始值被设置为False,所以while循环根本不应该执行。

# The player gets 3 chances to guess the secret word
# If guessed correctly within the given chances, the player wins
# If guessed incorrectly and there are no more chances, the player loses

secret_word = "Red"
guess = ""
counter = 0
guess_limit = 3
guesses_complete = False

while guess != secret_word and not(guesses_complete):
    if counter < guess_limit:
        guess = input("Enter guess: ")
        counter += 1
    else:
        guesses_complete = True

if guesses_complete:
    print("Loser")
else:
    print("Winner")

代码按原样编写,但我不知道为什么。我很确定只是我对not() 运算符的理解很弱。如果有人为我解决这个问题,我将不胜感激。

【问题讨论】:

  • 首先,not(guesses_complete) 等价于not guesses_complete。其次,not 是一个布尔运算符。

标签: python boolean boolean-logic boolean-expression boolean-operations


【解决方案1】:

not() 的工作方式确实与您的想法相反。在这种情况下not(guesses_complete) 与使用guesses_complete == False 相同。如果是guesses_complete == False,则该语句将返回True,这意味着应该执行while循环。当guesses_complete 的值设置为False 时,not(guesses_complete) 也会发生这种情况。

【讨论】:

  • 啊,我明白了。将not(guesses_complete)guesses_complete == False 视为同一件事确实有助于我的思考
【解决方案2】:

not 关键字是逻辑运算符。如果语句不为真,则返回值为真,如果语句不为假,则返回值为假。 Source。在上面的代码中,我们希望用户玩到他有一些猜测为止,即,如果guesses_complete 为 False,我们希望循环执行。

【讨论】:

    【解决方案3】:

    not 关键字反转布尔值(真或假值),将 True 转换为 False。这意味着如果您希望在变量为假的情况下运行一段代码,而不是使用not,您可以运行该代码。帮助示例:

    finished_game = False
    while not finished_game:#While the game isn't finished
        #run game code
    

    这有意义吗?根据我的经验,not 关键字意味着您可以将False 用作True

    希望能有所帮助。

    【讨论】:

    • 哦,我不是这么想的。我在想,not 检查布尔值是否与代码中写的相反,然后才执行代码。相反,如果布尔值为False,我应该将其视为not 执行代码
    【解决方案4】:

    我相信 not() 运算符的计算结果相反。因此,如果它设置为假,它会将变量切换为真,如果初始变量值为真,则 not() 将其设置为假。我认为它是一个相反的日子功能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-15
      • 2020-08-09
      • 2014-06-06
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多