Make delicious recipes!

Variable and named arguments to functions



Named arguments:

>>> def func(a,b,c):
...   print (a, b, c)
...


>>> func (1,2,3)    # positional arguments example  
1 2 3


>>> func (c=1, b=2, a=3)   # named arguments example     
3 2 1




Variable number of arguments can be sent in 2 ways:
  1. * is used to specify variable number of positional arguments.
  2. ** is used to specify variable number of named arguments.
# args3 receives variable number of positional arguments.
# args4 receives variable number of named arguments.
>>> def varArgsFunc (arg1, arg2, *args3, **args4):
...   print (arg1)
...   print (arg2)
...   for arg in args3:
...     print (arg)
...   keys = sorted (args4.keys())
...   for key in keys:
...     print (key, ":", args4[key])
...


# The above function can be called with variable number of arguments as follows:   
>>> varArgsFunc (
  32, 
  'hello', 
  'var-arg1', 2, 'var-arg3', 4.0, 
  mapArg1=1, mapArg2='two', seven=(4,3,'four','three')
)

Response:
32
hello
var-arg1
2
var-arg3
4.0
mapArg1 : 1
mapArg2 : two
seven : (4, 3, 'four', 'three')










Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal