【问题标题】:While True or while 1? [duplicate]当真或当1? [复制]
【发布时间】:2012-02-15 17:29:07
【问题描述】:

可能重复:
while (1) Vs. for while(True) — Why is there a difference?

我有时会在其他人的代码中看到“while 1”而不是“while True”。 我认为使用 True 更pythonic,但我想检查是否有 实践中的任何差异。

所以我尝试了以下操作,结果令人惊讶。为了什么 我可以看到解释器看起来可以优化掉 1 布尔值 转换,而它不与 True,与我相反 应该的。

谁能解释我为什么会这样,或者我的结论是错误的?

def f1():
    while 1:
        pass

def f2():
    while True:
        pass

In [10]: dis.dis(f)
2           0 SETUP_LOOP               3 (to 6)

3     >>    3 JUMP_ABSOLUTE            3
      >>    6 LOAD_CONST               0 (None)
            9 RETURN_VALUE

In [9]: dis.dis(f1)
2           0 SETUP_LOOP              10 (to 13)
      >>    3 LOAD_GLOBAL              0 (True)
            6 POP_JUMP_IF_FALSE       12

3           9 JUMP_ABSOLUTE            3
      >>   12 POP_BLOCK
      >>   13 LOAD_CONST               0 (None)
           16 RETURN_VALUE

【问题讨论】:

  • 这并不重要,因为可能真正的代码没有通过。所以更喜欢可读性。

标签: python interpreter bytecode


【解决方案1】:

编译器无法优化对 True 的引用,因为不幸的是,在 python 2 中我可以这样做:

True = []
if not True:
    print "oops" # :-(

幸运的是,在 python 3.2 中我得到了SyntaxError: assignment to keyword

【讨论】:

    猜你喜欢
    • 2014-10-18
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多