When we are unsure about the number of agrument to pass in the function, we can use
Python *args : Non Keyword Arguments
- *args allow us to pass the variable number of non keyword arguments to function.
- In the function definition, we should use an asterisk * before the parameter name to pass variable length arguments. The arguments are passed as a tuple and these passed arguments make tuple inside the function with same name as the parameter excluding asterisk *.
def addnumbers(*args):
return sum(args)*.05
addnumbers(40,60,20)
def addnumbers(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum is : "+ sum)
adder(6,5)
adder(6,7,8,4,8)
Python **kwargs : Keyword Arguments
- It allows us to pass the variable length of keyword arguments to the function.
- In the function definition, we should use double asterisk ** before the parameter name to pass variable length arguments. The arguments are passed as a dictionary and these arguments make a dictionary inside function with name same as the parameter excluding double asterisk **.
def myfunc(**fr):
if 'fruit' in fr:
print(f"My favorite fruit is {fr['fruit']}")
else:
print("I don't like fruit")
myfunc(fruit='Mango') # My favorite fruit is Mango
myfunc() # I don't like fruit
Python *args and **kwargs combined:
- We can pass *args and **kwargs into the same function, but *args have to appear before **kwargs. Otherwise it will throw an exception as "SyntaxError: positional argument follows keyword argument"
def myfunc(*args, **kwargs):
if 'fruit' and 'juice' in kwargs:
print(f"I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}")
print(f"May I have some {kwargs['juice']} juice?")
else:
pass
myfunc('eggs','spam',fruit='cherries',juice='orange')
o/p:
I like eggs and spam and my favorite fruit is cherries
May I have some orange juice?