有没有理由在Python中使用"while 1,do something,break"?

Wat*_*uck 4 python sympy while-loop

在Python库SymPy我试着去理解函数partitions()sympy.utilities.iterables:

它是这样开始的:

def partitions(n, m=None, k=None, size=False):
    """Generate all partitions of integer n (>= 0).
Run Code Online (Sandbox Code Playgroud)

我对以下while循环感到困惑,因为它看起来毫无意义.如果我删除while 1:break它应该没有什么区别.但是,我希望开发SymPy的人知道他们在做什么,并且不会犯很简单的错误.那么这是否意味着我没有看到?

while 1:
    # Let i be the smallest key larger than 1.  Reuse one instance of i.
    i = keys[-1]
    newcount = ms[i] = ms[i] - 1
    reuse += i
    if newcount == 0:
        del keys[-1], ms[i]
    room += 1

    # Break the remainder into pieces of size i-1.
    i -= 1
    q, r = divmod(reuse, i)
    need = q + bool(r)
    if need > room:
        if not keys:
            return
        continue

    ms[i] = q
    keys.append(i)
    if r:
        ms[r] = 1
        keys.append(r)
    break
Run Code Online (Sandbox Code Playgroud)

出于学习目的,我简化了整个功能,并my_partitions(n)给出了相同的结果partitions(n).

def my_partitions(n):
    ms = {n: 1}
    keys = [n]
    yield ms

    while keys != [1]:
        # Reuse any 1's.
        if keys[-1] == 1:
            del keys[-1]
            reuse = ms.pop(1)
        else:
            reuse = 0

        # Let i be the smallest key larger than 1.  Reuse one instance of i.
        i = keys[-1]
        ms[i] -= 1
        reuse += i
        if ms[i] == 0:
            del keys[-1], ms[i]

        # Break the remainder into pieces of size i-1.
        i -= 1
        q, r = divmod(reuse, i)
        ms[i] = q
        keys.append(i)
        if r:
            ms[r] = 1
            keys.append(r)

        yield ms
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 7

这是一个将goto带到Python 的肮脏黑客.该while 1:行是标签,continue声明是goto.

如果可以避免,请不要编写类似的代码.如果你必须这样做,至少做到这一点,while True:因为参数to while通常是一个布尔值.