Python 脚本 "executing file" 永远

Python script "executing file" forever

这是我的脚本:

def encodage(message):
    """
    begins our binary qrcode with the type of the message:
    binary, numeric or alphanumeric (string)
    """
    qrcode = []



    if type(message) == str: #string
        qrcode = [0,0,1,0] + qrcode

    else: 
        if type(message) == list: #list can contain numeric and alphanumeric
            if type(message[0]) == int:
                bit = True

                while bit:
                    for n in message:
                        if (n != 0) and (n != 1): #verifying if binary
                            bit = False
                if bit:
                    qrcode = [0,1,0,0] + qrcode
                else:
                    qrcode = [0,0,0,1] + qrcode

            if type(message[0]) == str:
                qrcode = [0,0,1,0] + qrcode
    return qrcode

我觉得它的作用已经很清楚了。当我 运行 它具有以下内容时:

message = [0,1,1,1,1]

print(encodage(message))

没有给出答案,就是永远的轮回

我认为问题出在我奇怪的二进制测试循环(它适用于 message = "salut")。

你怎么看?感谢阅读。

看不到自己的状态吗?

message = [0,1,1,1,1]

bit = True
while bit:
  for n in message:
    if (n != 0) and (n != 1): #verifying if binary
     bit = False

这个

if (n != 0) and (n != 1): #verifying if binary

将始终 return False 从而永远循环,只需将您的输入(消息)与此 if 语句进行比较,看看它是否有意义

感谢几位评论,这里更正:

    if type(message) == list:
        if type(message[0]) == int:
            bit = True

            for n in message:
                if (n != 0) and (n != 1):
                    bit = False

谢谢大家

while 循环没有任何好处。只需删除 while。在结果中添加一个空列表也没有意义:

def encodage(message):
    """
    begins our binary qrcode with the type of the message:
    binary, numeric or alphanumeric (string)
    """
    if isinstance(message, str):
        qrcode = [0,0,1,0]
    elif isinstance(message, list):
        if isinstance(message[0], int):
            # verifying if binary
            bit = all(n in (0, 1) for n in message)
            qrcode = [0,1,0,0] if bit else [0,0,0,1]
        elif isinstance(message[0], str):
            qrcode = [0,0,1,0]
        else:
            qrcode = []
    else:
        qrcode = []
return qrcode