【问题标题】:Why can't a previously assigned variable be used while defining a function? [closed]为什么在定义函数时不能使用先前分配的变量? [关闭]
【发布时间】:2019-04-09 13:01:44
【问题描述】:

下面是我试图用来运行函数的 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: 'function' 对象不可迭代

【问题讨论】:

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

标签: python python-3.x function typeerror


【解决方案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 变成了一个变量而不是一个函数。所以会产生错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-06
    • 2014-12-05
    • 2020-01-31
    相关资源
    最近更新 更多