defmyFun(*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
# *args is a Variable Length Argument of type Tuple,# which takes any number of parameters, including 0 number of arguments as well.defvariableLengthArguments(*args):print(sum(args))
variableLengthArguments()# Output: 0
variableLengthArguments(10)# Output: 10
variableLengthArguments(10,20)# Output: 30
variableLengthArguments(10,20,30,50,90)# Output: 200
defmul(*args):# args as argument
multiply =1for i in args:
multiply *= i
return multiply
lst =[4,4,4,4]
tpl =(4,4,4,4)print(mul(*lst))# list unpackingprint(mul(*tpl))# tuple unpacking
# Python program to illustrate # **kwargs for variable number of keyword arguments definfo(**kwargs):for key, value in kwargs.items():print("%s == %s"%(key, value))# Driver code
info(first ='This', mid ='is', last='Me')
deffunc(*args):
x =[]# emplty listfor i in args:
i = i *2
x.append(i)
y =tuple(x)# converting back list into tuplereturn y
tpl =(2,3,4,5)print(func(*tpl))
# if args is not passed it return message# "Hey you didn't pass the arguements"defech(nums,*args):if args:return[i ** nums for i in args]# list comprehensionelse:return"Hey you didn't pass args"print(ech(3,4,3,2,1))
# Python program to illustrate # *kwargs for variable number of keyword argumentsdefmyFun(**kwargs):for key, value in kwargs.items():print("%s == %s"%(key, value))# Driver code
myFun(first ='Geeks', mid ='for', last='Geeks')''' output:
last == Geeks
mid == for
first == Geeks
'''
# normal parameters with *argsdefmul(a,b,*args):# a,b are normal paremeters
multiply =1for i in args:
multiply *= i
return multiply
print(mul(3,5,6,7,8))# 3 and 5 are being passed as a argument but 6,7,8 are args
defwrap(*args):
lis =list(args)# it is important to convert args into list before looping, args take tuple as a argument for i inrange(len(lis)):
lis[i]= lis[i]*2
args =tuple(lis)return args
print(wrap(2,3,4,5,6))
# if args is not passed it return message# "Hey you didn't pass the arguements"defech(num,*args):if args:
a =[]for i in args:
a.append(i**num)return a # return should be outside loopelse:return"Hey you didn't pass the arguements"# return should be outside loopprint(ech(3))
defmyFun(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)