python 3 typeError:'NoneType'对象不可迭代

我写了下面的代码来找到*args的继承。但我有一个错误。我真的不明白这个错误,因为我有输入,但他们不是没有。


def third(*args, option=True):

    if len(args) == 2:

        word1, word2 = args

    else:

        word1 = args[0]


    if option:

        return word1, word2

    else:

        return word1



def hello(data, *args, option=True):

    print("the data is:", data)

    A, B = third(*args, option=True)

    print("the args are:", A, B)


def world(small, *args, option=True):

    return hello(small, *args)



if __name__ == "main":

    world("data","prediction")

输出:


the data is: data

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "<stdin>", line 2, in world

File "<stdin>", line 3, in hello

TypeError: 'NoneType' object is not iterable


慕码人8056858
浏览 203回答 2
2回答

斯蒂芬大帝

试试这个,应该工作:def third(*args):&nbsp; &nbsp; if len(args) == 2:&nbsp; &nbsp; &nbsp; &nbsp; word1, word2 = args&nbsp; &nbsp; &nbsp; &nbsp; option = True&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; option = False&nbsp; &nbsp; &nbsp; &nbsp; word1 = args[0]&nbsp; &nbsp; if option:&nbsp; &nbsp; &nbsp; &nbsp; return word1, word2&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return word1, Nonedef hello(data, *args):&nbsp; &nbsp; print("the data is:", data)&nbsp; &nbsp; A, B = third(*args)&nbsp; &nbsp; print("the args are:", A, B)def world(small, *args):&nbsp; &nbsp; return hello(small, *args)if __name__ == "__main__":&nbsp; &nbsp; world("data","prediction")

肥皂起泡泡

基本上你正在传递 options=True 这意味着“第三个”函数应该总是返回 word1 和 word2。但是 args 的 len 是一个,因此根据您的 if len(args) == 2 条件,word2 不存在。所以“第三个”函数只返回word1。在您的“hello”函数中,您试图通过 A, B =third(arguments) 方法将该单个元素映射到两个变量“A”和“B”,该方法迭代函数的返回值,但它无法这样做,因为第三是返回一个元素或一个错误值(因为您试图返回不存在的 word2)。这就是发生此错误的原因
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python