【发布时间】: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