Python - While 假循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22377668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:49:18  来源:igfitidea点击:

Python - While false loop

pythonloopspython-3.xwhile-loopboolean

提问by Phoenix

fn='a'
x=1

while fn:
    print(x)
    x+=1
    if x==100:
        fn=''

Output: 1 ... 99

输出:1 ... 99

fn=''
x=1

while fn:
    print(x)
    x+=1
    if x==100:
        fn='a'

Output: while loop does not run.

输出:while 循环不运行。



What is the reason for the while loop not running?

while循环没有运行的原因是什么?

Is it that the condition that ends a while loop is 'False' and therefore it's not capable of performing 'while false' iterations?

是否结束 while 循环的条件是“假”,因此它不能执行“while false”迭代?

采纳答案by Silas Ray

If you want 'while false' functionality, you need not. Try while not fn:instead.

如果您想要“while false”功能,则需要not. 试试吧while not fn:

回答by Pablo Francisco Pérez Hidalgo

Consider your loop condition to be translated into this:

考虑将您的循环条件转换为:

fn=''
x=1

while len(fn)>0:
    print(x)
    x+=1
    if x==100:
        fn='a'

whilechecks if the string is not empty at the beginning of each iteration.

while在每次迭代开始检查字符串是否为空。

回答by Arovit

In python conditional statements :

在 python 条件语句中:

''is same as Falseis same as 0is same as []

''相同False相同0相同 相同[]

回答by aragaer

The condition is the loop is actually a "pre-" condition (as opposed to post-condition "do-while" loop in, say, C). It tests the condition for each iteration including the first one.

条件是循环实际上是一个“前”条件(而不是后条件“do-while”循环,比如说,C)。它测试包括第一次在内的每次迭代的条件。

On first iteration the condition is false, thus the loop is ended immediately.

在第一次迭代时,条件为假,因此循环立即结束。