Ashish Prajapati
Ashish Prajapati

Reputation: 36

Default argument and variable-length argument in python

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'

Upvotes: 0

Views: 257

Answers (2)

Alexandru Martalogu
Alexandru Martalogu

Reputation: 273

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'

Upvotes: 1

Shintlor
Shintlor

Reputation: 812

Try switching the arguments:

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

This should work.

Upvotes: 0

Related Questions