Python 为什么可以';定义函数时是否使用以前指定的变量?

Python 为什么可以';定义函数时是否使用以前指定的变量?,python,python-3.x,function,typeerror,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 fun

下面是我试图用来运行函数的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()
我不明白为什么我们需要变量“利益列表”,为什么我们不能在最后一个函数中直接使用“利益列表”。上面的代码运行得很好,但是如果我从任何地方删除“利益列表”,我会得到下面的错误-

TypeError:“函数”对象不可编辑

您可以直接在循环中使用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!
如果您想这样做,请不要这样做(我相信您很可能在尝试时出错):


这对你来说是行不通的,因为在这种情况下,列表变成了一个变量,而不是一个函数。所以它会产生一个错误

您必须执行
list\u benefits()
而不是
list\u benefits
,注意括号,这就是调用函数的方式,否则,您只是引用函数对象本身。请澄清您的问题。您可以直接使用list_benefits()作为for循环目标。
for benefi in list_benefits: