python - 单个函数的参数数量可变

标签 python python-3.x

我尝试了一些代码,但没有得到满意的答案。代码的输出应该是来自调用站点的确切数字参数:

>>> def  Hello(PitU,*V):
    print("you passed" , PitU,"Arguments")
    for Pit in V:
        print(Pit)

#case1      
>>> Hello(3,"one","two","three")
you passed 3 Arguments
one
two
three

#case2
>>> Hello(3,"one","two")
you passed 3 Arguments
one
two

#case3
>>> Hello(3,"one","two","three","four")
you passed 3 Arguments
one
two
three
four
>>> 

我希望输出是:

A. case-1
you passed 3 Arguments
one
two
three

B. case-2
error

C. case-3
error

instead of 

Case1
you passed 3 Arguments
one
two
three

case2
you passed 3 Arguments
one
two

case3
you passed 3 Arguments
one
two
three
four

最佳答案

为此你需要自己检查,python 不会为你做。

def Hello(PitU, *V): 
    if len(V) != PitU:
        print("error")
        return
    print("you passed", PitU, "Arguments") 
    for Pit in V: 
        print(Pit)

关于python - 单个函数的参数数量可变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55633248/

相关文章:

python selenium点击多个调查按钮错误

python - 子列表的唯一元素取决于子列表中的特定值

python - 有没有办法在大括号内分解 f 弦?

python - Python 中与 finditer() 的重叠匹配

python - 如何将二进制文件打印为字节?

python - PyCharm:为什么只显示退出代码行?

python - PostParameters 列表(Python 请求)

python - 如何在 python 中使用 nltk 识别字符串中的颜色?

python - 多维 numpy 矩阵的旋转和翻转

python - 使用 dictwriter 覆盖同一 csv 文件中的行