1

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)
5
  • so you want to call it without a and with b? why? but i think average(b=(1,2,3)) should work... Commented Dec 4, 2017 at 16:58
  • " in a method like this how can call this method without supplying value for a" - Do you want a default value for a? Commented Dec 4, 2017 at 16:59
  • hey, you want answer on a=5, *b or *a, b? Commented Dec 4, 2017 at 16:59
  • 1
    That is a function not a method Commented Dec 4, 2017 at 17:17
  • @M.Volf average(b=(1,2,3)) is not working. Commented Dec 5, 2017 at 14:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

8 Comments

@MosesKoledoye: Given that Python 2.7 is nearing EOL in about 2 years... seems like a good time to migrate over.
what i have got from answers from all is if function is average(*a,b) then we need to specify average(1,2,3,b=4) and if we have average(a=5,*b) and we need to call without passing a then average(b=(2,3,4)). thanks
i am able to run average(1,2,3,b=4) but running average(b=(1,2,3)) is not working and generates an error TypeError: average() got an unexpected keyword argument 'b'. Can anybody update
The first method shown in this answer already works with average(b=(1,2,3)). The argument a will take the empty tuple here.
@wim but second one is not working i.e average(a=5,*b) is not working for average(b=(1,2,3))
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.