xxxxxxxxxx
def myFun(*args,**kwargs):
print("args: ", args)
print("kwargs: ", kwargs)
myFun('my','name','is Maheep',firstname="Maheep",lastname="Chaudhary")
# *args - take the any number of argument as values from the user
# **kwargs - take any number of arguments as key as keywords with
# value associated with them
xxxxxxxxxx
>>> def argsKwargs(*args, **kwargs):
print(args)
print(kwargs)
>>> argsKwargs('1', 1, 'slgotting.com', upvote='yes', is_true=True, test=1, sufficient_example=True)
('1', 1, 'slgotting.com')
{'upvote': 'yes', 'is_true': True, 'test': 1, 'sufficient_example': True}
xxxxxxxxxx
############################# ARGS ###########################################
def my_function(*kids):
print(kids)
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
>>>('Emil', 'Tobias', 'Linus')
The youngest child is Linus
############################# KWARGS #########################################
def my_function(**kid):
print(kid)
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
>>>{'fname': 'Tobias', 'lname': 'Refsnes'}
His last name is Refsnes
xxxxxxxxxx
# first with *args
>>> args = ("two", 3, 5)
>>> test_args_kwargs(*args)
arg1: two
arg2: 3
arg3: 5
# now with **kwargs:
>>> kwargs = {"arg3": 3, "arg2": "two", "arg1": 5}
>>> test_args_kwargs(**kwargs)
arg1: 5
arg2: two
arg3: 3
xxxxxxxxxx
# Python program to illustrate
# **kwargs for variable number of keyword arguments
def info(**kwargs):
for key, value in kwargs.items():
print ("%s == %s" %(key, value))
# Driver code
info(first ='This', mid ='is', last='Me')
xxxxxxxxxx
def foo(*args):
for a in args:
print(a)
foo(1)
# 1
foo(1,2,3)
# 1
# 2
# 3
xxxxxxxxxx
def test_args_kwargs(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
xxxxxxxxxx
def myFun(arg1, arg2, arg3):
print("arg1:", arg1)
print("arg2:", arg2)
print("arg3:", arg3)
# Now we can use *args or **kwargs to
# pass arguments to this function :
args = ("Geeks", "for", "Geeks")
myFun(*args)
kwargs = {"arg1": "Geeks", "arg2": "for", "arg3": "Geeks"}
myFun(**kwargs)