Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 而不是表达式和布尔理解_Python_Boolean - Fatal编程技术网

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