Python 而不是表达式和布尔理解
我发现这个是为了生成随机数Python 而不是表达式和布尔理解,python,boolean,Python,Boolean,我发现这个是为了生成随机数 def main(): randomNumber = randint(1,100) found = False while not found: userGuess = input("") if userGuess == randomNumber: print "You win." found = True elif .....
def main():
randomNumber = randint(1,100)
found = False
while not found:
userGuess = input("")
if userGuess == randomNumber:
print "You win."
found = True
elif
.....
else
.....
所以我的问题是“虽然没有找到”,我不觉得这是本能的。
更本能但不起作用的应该是:
found = False
while found
-->“查找”为false时循环正在工作
有人能解释一下吗?当给定表达式为
True
时,将执行while
循环。在您的情况下,给定的表达式是未找到
。由于found
以False
开头,因此notfound
当然是True
,因此循环将执行并继续执行,直到found
设置为True
,此时notfound
将是False
我的建议是不要重写这篇文章——它实际上是非常可读的。你是说当你发现了某个东西时,继续寻找。如果
当你没有发现时,你似乎没有感觉,你应该习惯它。这是一个常见的Python习惯用法,过一段时间后看起来会非常直观(双关语)
但是,如果您想要更可读的代码,我会完全去掉found
变量,并使用break
终止循环:
def main():
randomNumber = randint(1,100)
while True:
userGuess = input("")
if userGuess == randomNumber:
print "You win."
break
# Code here will run only if the break isn't executed.
# You don't need the elif any more.
这是个人偏好的问题:有些人喜欢使用标志变量来终止循环;我更喜欢这样的显式插入代码的简单性。那么你应该编写while found==false
这是文本的直译,“while found is false”<代码>找到时
表示找到时==True
和未找到时
表示找到时==False