"while False" 是什么意思意思是? [英] What does "while False" mean?

查看:133
本文介绍了"while False" 是什么意思意思是?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白这段代码是如何工作的:

I don't undestand how this code works:

i = 1
while False:
    if i % 5 == 0:
        break
    i = i + 2
print(i)

while False 是什么?什么是假的?我不明白...

what does while False? What does it have to be false? I don't get it...

推荐答案

A while循环在每次迭代之前检查while后面的条件(好吧,表达式),当条件为False时停止执行循环体.

A while loop checks the condition (well, the expression) behind the while before each iteration and stops executing the loop body when the condition is False.

所以 while False 意味着循环体永远不会执行.循环内的一切都是死代码".因此,Python-3.x 会优化"while 循环:

So while False means that the loop body will never execute. Everything inside the loop is "dead code". Python-3.x will go so far that it "optimizes" the while-loop away because of that:

def func():
    i = 1
    while False:
        if i % 5 == 0:
            break
        i = i + 2
    print(i)

import dis

dis.dis(func)

给出以下内容:

  Line        Bytecode

  2           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (i)

  7           6 LOAD_GLOBAL              0 (print)
              9 LOAD_FAST                0 (i)
             12 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             15 POP_TOP
             16 LOAD_CONST               0 (None)
             19 RETURN_VALUE

这意味着编译后的函数甚至不知道存在while 循环(第3-6 行没有说明!),因为while 不可能代码>-loop可以被执行.

That means the compiled function won't even know there has been a while loop (no instructions for line 3-6!), because there is no way that the while-loop could be executed.

这篇关于"while False" 是什么意思意思是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆