Function Arguments

Different Types of Function Arguments in Python.

Python - Function Arguments:

Functions can accept arguments, which are the values passed to the function when it is called. Function arguments can be of different types and can be used to pass data into the function for processing. There are several types of function arguments in Python:


1. Positional Arguments: These are the arguments passed to a function in the order they are defined. The position of the argument determines which parameter it will be assigned to in the function definition.

PDF Copy Code
# Python function: Positional Arguments
def greet(name, age):
    print(f"Hello, {name}. You are {age} years old.")


greet("Ayan", 28)
Output:
Hello, Ayan. You are 28 years old.

2. Keyword Arguments: These are arguments passed with the parameter name explicitly specified. This allows you to pass arguments in any order, as long as you specify the parameter names.

PDF Copy Code
# Python function: Keyword Arguments
def greet(name, age):
    print(f"Hello, {name}. You are {age} years old.")


# Order doesn't matter because of keyword arguments
greet(age=28, name="Ayan")
Output:
Hello, Ayan. You are 28 years old.

3. Default Arguments: These are arguments with default values specified in the function definition. If the caller does not provide a value for these arguments, the default value is used.

PDF Copy Code
# Python function: Default Arguments
def greet(name, message="How are you?"):
    print(f"Hello, {name}! {message}")


greet("Ayan")
Output:
Hello, Ayan! How are you?

4. Variable-Length Arguments: Python allows you to define functions that can accept a variable number of arguments. There are two types of variable-length arguments:

a. *args: This is used to pass a variable number of positional arguments to a function. The function receives them as a tuple.

PDF Copy Code
# Python function: Variable-Length Arguments
def sum_values(*args):
    total = 0
    for num in args:
        total += num
    return total


print(sum_values(1, 2, 3, 4))
Output:
10

5. **kwargs: This is used to pass a variable number of keyword arguments to a function and the function receives them as a dictionary.

PDF Copy Code
# Python function: **kwargs Arguments
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")


print_info(name="Ayan", age=28, city="BHP")
Output:
name: Ayan
age: 28
city: BHP

Note: These are the basic types of function arguments in Python, and they offer flexibility in how you can define and call functions.

What's Next?

We actively create content for our YouTube channel and consistently upload or share knowledge on the web platform.