【问题标题】:Why is this function not returning anything in the interactive shell? [duplicate]为什么这个函数在交互式 shell 中没有返回任何东西? [复制]
【发布时间】:2020-06-17 12:41:52
【问题描述】:

当我编写此代码然后将add_two_cents(mylist) 写入交互式外壳时,我没有得到任何回报。它只是移动到下一行。

mylist = ["kiwi", "apple"]
def add_two_cents(mylist):
  mylist.append("two cents")

【问题讨论】:

  • 因为你的函数没有返回任何东西。
  • 虽然它没有被格式化为代码,但你的函数似乎没有return 语句,所以它不会返回任何东西。您似乎也没有在任何地方调用该函数。您能否更具体地说明您的期望?
  • 调用函数后你期望发生什么?该函数不返回任何内容,但 mylist 变量被修改。
  • list.append docs.python.org/2/tutorial/datastructures.html#more-on-lists 不返回任何内容,只是将项目附加到现有列表中。

标签: python function


【解决方案1】:

首先,如果你在你的函数中省略return,它和写return None是一样的。所以你的函数确实返回 None 但你看不到,因为默认情况下 None 不会出现在交互式 REPL shell 中。这就是为什么你什么都看不到的原因。

此外,如果您想要查看某些内容,您可能想要查看修改后的列表。所以你应该在函数末尾添加return mylist

最后,由于mylistlist 类型,您正在更改一个可变变量并且根本不需要 返回列表。只需再次打印它,看看它是否发生了变化。

【讨论】:

    【解决方案2】:

    您没有返回任何内容,因此它不会在解释器中打印任何内容。但是列表可变的,因此如果您不想返回,则不必返回,但如果您想查看更改,则需要打印列表。请注意,我已在函数外部重命名 mylist 用法,以明确哪个是函数变量,哪个是本机变量。

    def add_two_cents(mylist);
      mylist.append("two cents")
      pass #just to point out end of function
    
    
    foo = ["kiwi", "apple"]
    add_two_cents(foo)
    print(str(foo)) # this will print a string representation of foo
    

    【讨论】:

      【解决方案3】:
      mylist = ["kiwi", "apple"]
      def add_two_cents(mylist):
         mylist.append("two cents")
         return mylist
      

      你只需要在“return”语句处

      【讨论】:

        猜你喜欢
        • 2015-10-10
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        相关资源
        最近更新 更多