为什么在定义函数时不能使用先前分配的变量?

时间:2018-11-06 06:30:29

标签: python python-3.x function typeerror

下面是我试图用来运行函数的python代码。

def list_benefits():
    return "More organized code", "More readable code", "Easier code 
    `reuse", "Allowing programmers to share and connect code together"`


def build_sentence(benefit):
    return "%s is a benefit of functions!" %benefit


def name_the_benefits_of_functions():
    list_of_benefits = list_benefits()
    for benefi in list_of_benefits:
        print(build_sentence(benefi))


name_the_benefits_of_functions()

我不明白为什么我们需要有变量'list_of_benefits',为什么我们不能在最后一个函数中直接使用'list_benefits'。上面的代码运行良好,但是如果我从各处删除“ list_of_benefits”,则会收到以下错误-

TypeError:“函数”对象不可迭代

1 个答案:

答案 0 :(得分:1)

您可以直接在循环中使用list_benefits()。查看以下代码:

def list_benefits():
    return "More organized code", "More readable code", "Easier code","reuse", "Allowing programmers to share and connect code together"

def build_sentence(benefit):
    return "%s is a benefit of functions!" %benefit

def name_the_benefits_of_functions():
    for benefi in list_benefits():
        print(build_sentence(benefi))

name_the_benefits_of_functions()

对我来说很好。输出:

More organized code is a benefit of functions!
More readable code is a benefit of functions!
Easier code is a benefit of functions!
reuse is a benefit of functions!
Allowing programmers to share and connect code together is a benefit of functions!

请不要这样做(我相信您很可能在尝试此操作时遇到错误):

for benefi in list_benefits:

它对您不起作用,因为在这种情况下list_benifits成为变量而不是函数。因此它将产生一个错误。