Skip to main content
 首页 » 编程设计

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

2025年05月04日1352php

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

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