单个函数的可变参数数

2024-10-01 13:25:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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

>>> 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

Tags: 代码youhelloargumentsonethreefourcase
2条回答

为此,您需要自己进行检查,python不会为您这样做。你知道吗

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

因为PITu不是你必须传递的参数数,它只是你放在那里的另一个参数。python技术没有错,只是误解了它的概念。你知道吗

相关问题 更多 >