Preeti Gupta
Preeti Gupta

Reputation: 19

Variable number of arguments to a single function

I tried some code but I am not getting a satisfactory answer. The output of the code should be the exact number arguments from the call site:

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

I expect the output to be:

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

Upvotes: 1

Views: 71

Answers (2)

Abd El Kodous Souissi
Abd El Kodous Souissi

Reputation: 355

Because PITu isn't the number of the arguments you must pass, it's just another argument you put there. there is nothing wrong with python technique, you just misunderstood its concept.

Upvotes: 3

Shuvojit
Shuvojit

Reputation: 1470

For that you need to put a check yourself, python won't do that for you.

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

Upvotes: 3

Related Questions