【问题标题】:Python: List of input variables in a parameterized functionPython:参数化函数中的输入变量列表
【发布时间】:2022-12-07 23:46:43
【问题描述】:

我是 python 的新手,我正在尝试从用户那里获取值列表并在函数中使用它们,这是我的代码:

def functionwithList(*words):

    for i in words:
        print(f"this is part of the words list: {i}")



param1,param2 = functionwithList(input('enter two numbers').split())

当我执行代码时,我得到以下输出以及 Cannot unpack non-iterable NoneType Object

enter two numbers1 2
this is part of the words list: ['1', '2']
Traceback (most recent call last):
  File "I:\DataScience_BootCamp\PythonBootcampSession2\Demo\Session_4.py", line 16, in <module>
    param1,param2 = functionwithList(input('enter two numbers').split())
TypeError: cannot unpack non-iterable NoneType object

有人可以解释这里有什么问题吗?

【问题讨论】:

  • 你期望functionwithList 返回什么?

标签: python


【解决方案1】:

如果 words 应该是一个字符串列表,那么更改

def functionwithList(*words):

def functionwithList(words):

另外 functionwithList 没有 return 任何东西,所以当你调用函数时没有解包

param1,param2 = functionwithList(...

你会想修改你的功能

def functionwithList(words):
    for i in words:
        print(f"this is part of the words list: {i}")
    return words

【讨论】:

    【解决方案2】:

    你的函数 functionwithList() 没有 return,所以它返回 None。您正在将 functionwithList() 的输出(即 None)解包到 param1,param2 = 中。解包 None 是不可能的,因此在 python 中是非法的。

    你必须在print之后使用return

    def functionwithList(words):
        for i in words:
            print(f"this is part of the words list: {i}")
        return words
    

    然后像这样使用它:

    param1,param2 = functionwithList(input('enter two numbers').split())
    

    【讨论】:

      【解决方案3】:

      从函数调用中删除 param1,param2。 或者在函数中加一个return。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-07
        相关资源
        最近更新 更多