首页 > 解决方案 > 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

标签: python

解决方案


基本上你传递 options=True 这意味着“第三个”函数应该总是返回 word1 和 word2。但是 len of args 是一个,所以 word2 根据你的 if len(args) == 2 条件不存在。

所以“第三个”函数只返回 word1。在您的“hello”函数中,您试图通过 A, B =third(arguments) 方法将该单个元素映射到两个变量“A”和“B”,该方法迭代函数的返回值,但它无法这样做,因为第三是返回一个元素或一个错误值(因为您试图返回不存在的 word2)。这就是发生此错误的原因


推荐阅读