python - 根据函数中参数的数量返回不同的值

标签 python python-3.x

<分区>

我正在尝试创建一个函数,该函数接受 1 到 5 个参数,并根据给定的数字进行不同的计算。 我的想法是这样的:

def function(*args)
    num_of_args = (!!here is the problem!!)
if(num_of_args == 1) : result = a
else if(number_of_args == 2) : result = a+b

等等 我试图计算参数的数量并将该数字分配给变量但找不到方法 我想可能不需要使用 5 个 if,但在我设法计算这些参数之前我真的不想专注于它

最佳答案

您可以使用len(args)

def function(*args):
    if len(args) == 0:
        print("Number of args = 0")
    elif len(args) == 1:
        print("Number of args = 1")
    else:
        print("Number of args >= 2")

关于python - 根据函数中参数的数量返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474811/

相关文章:

python - PySpark "illegal reflective access operation"在终端中执行时

python - 在 Tkinter.Tcl() 中使用 Python 函数

python - 如何用 Python 发送邮件

python - 使用 ctypes 和 wchar_t 时如何将字符串从 C++ 获取到 python?

python - 按日期和列名称匹配 2 个数据框以获取值

python - 尝试使用 urllib2 将 json 数据发送到 toggl api 时出现 HTTP 错误 400

python - 战舰游戏 - if/else 问题

android - os.system 不在同一个子 shell 中运行

python - 我在我的电脑上安装了python3.3.2,ubuntu12.04。还有埃里克 IDE

python-3.x - opencv 鱼脸识别器