简体   繁体   English

Python - 虚假循环

[英]Python - While false loop

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循环的条件是'False',因此它不能执行'while false'迭代吗?

If you want 'while false' functionality, you need not . 如果你想“而假”的功能,你需要not Try while not fn: instead. 尝试while not fn:相反。

The condition is the loop is actually a "pre-" condition (as opposed to post-condition "do-while" loop in, say, C). 条件是循环实际上是一个“预先”条件(而不是后置条件“do-while”循环,比方说,C)。 It tests the condition for each iteration including the first one. 它测试每次迭代的条件,包括第一次迭代。

On first iteration the condition is false, thus the loop is ended immediately. 在第一次迭代时,条件为假,因此循环立即结束。

In python conditional statements : 在python条件语句中:

'' is same as False is same as 0 is same as [] ''False相同, 0[]相同

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'

while checks if the string is not empty at the beginning of each iteration. while检查每次迭代开始时字符串是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM