args and kwargs python code example

Example 1: variable number of arguments to python class

def multiply(*args):
    z = 1
    for num in args:
        z *= num
    print(z)

multiply(4, 5)
multiply(10, 9)
multiply(2, 3, 4)
multiply(3, 5, 10, 6)

Example 2: use of kwargs and args in python classes

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

Example 3: *args,**kwarg

def intro(**data):
    print("\nData type of argument:",type(data))

    for key, value in data.items():
        print("{} is {}".format(key,value))

intro(Firstname="Sita", Lastname="Sharma", Age=22, Phone=1234567890)
intro(Firstname="John", Lastname="Wood", Email="[email protected]", Country="Wakanda", Age=25, Phone=9876543210)