Defining a Function with *args (Arbitrary Arguments)

Python function can have as many arguments as possible. But, you have to make sure pass the same number of argument values while calling the function. Otherwise, it throws the error message.

Example:

def multiply(num1, num2):
    print(“multiplication result”+ num1 * num2)

multiply(2, 5, 7).

In the above example, you are passing 3 argument values (2, 5, & 7) instead of 2 arguments as you defined the multiply() function with 2 parameters. So, this program throws the error message since you have passed 3 argument values.

To deal with this issue, you can use *args as parameter in Python function.

Example:

def multiply(*args):
    total = 0
    for num in args:
        total *= num
    print(“Total value”+ total)

multiply(2,3,4)         ## calling a function with 3 arguments
multiply(2,3,4,5)       ## calling a function with 4 arguments
multiply(2,3,4,5,6)     ## calling a function with 5 arguments
Calling a Function with keyword arguments

Python function can be called with key, and value pair arguments.
The big advantage with keyword arguments is you don’t require to follow the order of the arguments.

Example:

def employee(emp1, emp2, emp3):
print(“Employees are:”+emp1+” “+emp2+” “+emp3)

# calling a function without following order with key, value pair.
employee(emp2=”Tom”, emp3=”Josh”, emp1=”John”)


Related Tutorials