user2779311
user2779311

Reputation: 1884

how to call methods with multiple arguments

i am trying to learn python. in a method like average below how can call this method without supplying value for a means we only supply values for b. How will we call such a method.

def average(a=5 , *b):
    sum=0
    count=0
    print(" b is {0}".format(b))
    for bb in b:
        sum += bb
        count+=1
    av=(sum+a)/(count+1)
    return av

print("average is {0}".format(average(3,5,7,8,9,2)))

Here it takes a=3 and the rest as b. How can we call this method without value for a at all.

Can we have the first value as nargs like . If yes how do we supply the value of b.

def average(*a,b)

Upvotes: 1

Views: 84

Answers (1)

wim
wim

Reputation: 363566

def average(*a, b):
    ...

Using the syntax above, you must include b by keyword-only:

average(1,2,3,b=4)

If you don't like that, then just unpack inside the function directly like shown below:

def average(*args):
    *a, b = args
    ...

You will need to add handling for the case where args is empty.

Upvotes: 3

Related Questions