Multiple Function Arguments in Python

Python : Multiple Function Arguments

In Python, functions can take multiple arguments, including positional arguments, default arguments, and variable-length arguments.

In this tutorial, we will explore each of these types of arguments.

Positional Arguments

Positional arguments are the most common type of arguments in Python. They are simply arguments passed to a function in the order that they appear in the function call.

def greet(name, age):
    print(f"Hello, {name}! You are {age} years old.")

greet("Alice", 25)

In above example, name and age are positional arguments. When we call the function greet("Alice", 25), Python knows that Alice should be assigned to name and 25 should be assigned to age

Default Arguments

Default arguments are used when a function argument is optional. When a default argument is not provided, the default value is used instead.

def greet(name, age=30):
    print(f"Hello, {name}! You are {age} years old.")

greet("Alice")

In above example, age is a default argument with a default value of 30. When we call greet("Alice"), Python uses the default value for age.

Variable-Length Arguments

Sometimes we want to pass a variable number of arguments to a function. Python allows us to do this with variable-length arguments.

There are two types of variable-length arguments:

  1. *args

    *args is used to pass a variable number of positional arguments to a function

    def multiply(*args):
        result = 1
        for arg in args:
            result *= arg
        return result
    
    print(multiply(2, 3, 4))
    

    In above example *args allows us to pass a variable number of arguments to the multiply() function. The function multiplies all of the arguments together and returns the result.

  2. **kwargs.

    **kwargs is used to pass a variable number of keyword arguments to a function.

    def print_kwargs(**kwargs):
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    
    print_kwargs(name="Alice", age=25, city="New York")
    

    In above example, **kwargs allows us to pass a variable number of keyword arguments to the print_kwargs() function. The function prints out all of the key-value pairs in kwargs.

Combination of Arguments

Python allows us to use all of these types of arguments in the same function definition.

def func(arg1, arg2=42, *args, **kwargs):
    print(f"arg1={arg1}, arg2={arg2}, args={args}, kwargs={kwargs}")

func(1)
func(1, 2)
func(1, 2, 3, 4, 5, foo="bar", baz="qux")

In above example, we define a function func() that has a required argument arg1, a default argument arg2, variable-length positional arguments *args, and variable-length keyword arguments **kwargs. We then call the function with different combinations of arguments to demonstrate how they work.