0

In function I've defined two arguments 1:default variable say age=12 and 2:variable-length argument say *friends

    def variable(age=12,*friends):
         print 'Age:', age
         print 'Name:', friends
         return
    variable(15,'amit','rishabh') # RESULT is "Age: 15 & Name: 'amit', 'rishabh'
    variable('rahul','sourabh') # Now here result is Age: rahul & Name: 'sourabh' 

so my question is why function does'nt take both this arguments in *friends variable why it determine the first argument as age.

I need result should be in this format as:

variable(15,'name','surname') as Age:15 and Name: 'name','surname'

and if I don't assign age as

variable('new','name') Result needed to be as. Age:12 & Name:'new','name'
4
  • "why it determine the first argument as age." because that's how you defined your function. Commented Sep 10, 2018 at 7:03
  • how is your program supposed to know if the first argument is an age or a name? Maybe check for type if that's the behavior you are after... Commented Sep 10, 2018 at 7:04
  • The first argument will always be considered to be the age since you constructed your function this way. Commented Sep 10, 2018 at 7:05
  • try to pass a list for friends. Commented Sep 10, 2018 at 7:12

2 Answers 2

1

You could try to give in a list instead of various arguments, also keyword arguments should always go after aguments:

def variable(friends, age=12):
    print 'Age:', age
    print 'Name:', ",".join(friends)
    return
variable(['amit','rishabh'], 15) # RESULT is "Age: 15 & Name: 'amit', 'rishabh'
variable(['rahul','sourabh']) # Now here result is Age: rahul & Name: 'sourabh'
Sign up to request clarification or add additional context in comments.

Comments

0

Try switching the arguments:

def variable(*friends,age=12):
    print ('Age:', age)
    print ('Name:', friends)
    return

This should work.

5 Comments

This won't work, as if you given *args,**kwargs must follow, explicit arguments must come before, (name, age=12, *args, **kwargs) this is the correct syntax
You are correct that this may not follow the correct syntax. Nevertheless it does work. The OP should accept your answer though!
Are you sure? I'm trying it on Python 2.7 and my IDE is telling me Encountered "age" at line 268, column 23. Was expecting one of: "*" ... "**" ...
Also running the code is giving me a Syntax Exception, might be working on Python 3?
Yes, I am running python 3.6.6 and tested it in a jupyter notebook.

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.