【问题标题】:How to pass a list from one function to another? [duplicate]如何将列表从一个函数传递到另一个函数? [复制]
【发布时间】:2020-05-21 18:43:16
【问题描述】:

问题:在函数之间交换变量的想法。

我正在执行以下代码:

def benefits():
    list =  ["Beautiful", "Explicit", "Simple", "Readability","Easy to share"]
    return list

def statement(benefit):
    print("The benifit is " + benefit )          


def benefits_of_functions():  
    benefits_list = benefits()
    for benefit in benefits_list:
        print(statement(benefit))


benefits_of_functions()

我得到错误:

The benifit is Beautiful
None
The benifit is Explicit
None
The benifit is Simple
None
The benifit is Readability
None
The benifit is Easy to share
None

我无法理解“无”。你能帮我弄清楚为什么会出现在输出中吗?

【问题讨论】:

  • 因为你的statement 函数只是打印一些东西,并且不返回任何东西,所以它隐含地返回None。在benefits_of_functions 函数中,循环遍历列表,然后打印将列表中的项目传递给statement 的结果,这会打印您的消息,但您正在打印结果,即Nonedef statement 应该只是 return "The benifit is " + benefit 而不是 printing。
  • 注意,重要的是要理解,你不是将变量传递给函数,你传递的是对象

标签: python python-3.x list function


【解决方案1】:

statement 函数中返回而不是打印:

def benefits():
    list =  ["Beautiful", "Explicit", "Simple", "Readability","Easy to share"]
    return list

def statement(benefit):
    return "The benifit is " + benefit


def benefits_of_functions():  
    benefits_list = benefits()
    for benefit in benefits_list:
        print(statement(benefit))


benefits_of_functions()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-26
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 1970-01-01
    相关资源
    最近更新 更多