Function parameters

Types of Function Parameters

Python supports several types of parameters to accommodate a variety of function requirements.

Positional Parameters

Positional parameters are the most straightforward type. They must be provided in the same order as defined.

def add(a, b):
    return a + b

# Calling the function
result = add(2, 3)
print(result)  # Output: 5

Default Parameters

Default parameters have default values and are used if no corresponding argument is provided during the function call.

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

# Calling the function with and without the default parameter
print(greet("Alice"))  # Output: Hello, Alice!
print(greet("Bob", "Hi"))  # Output: Hi, Bob!

Keyword Parameters

Keyword parameters allow you to specify arguments by the parameter name, making the function call more readable and allowing parameters to be provided in any order.

def describe_pet(pet_name, animal_type='dog'):
    return f"I have a {animal_type} named {pet_name}."

# Calling the function with keyword arguments
description = describe_pet(animal_type='hamster', pet_name='Harry')
print(description)  # Output: I have a hamster named Harry.

Variable-Length Parameters

Variable-length parameters allow a function to accept an arbitrary number of arguments. There are two types: *args for non-keyword arguments and **kwargs for keyword arguments.

Using *args
def summarize(*numbers):
    return sum(numbers)

# Calling the function with a variable number of arguments
print(summarize(1, 2, 3))  # Output: 6
print(summarize(4, 5))  # Output: 9
Using **kwargs
def build_profile(**user_info):
    profile = {}
    for key, value in user_info.items():
        profile[key] = value
    return profile

# Calling the function with keyword arguments
user_profile = build_profile(first_name='John', last_name='Doe', age=30)
print(user_profile)  # Output: {'first_name': 'John', 'last_name': 'Doe', 'age': 30}

Positional-Only Parameters

Positional-only parameters are specified using a / in the function signature. Parameters before the / must be provided as positional arguments.

def f(a, b, /, c, d):
    return a + b + c + d

# Calling the function
print(f(1, 2, c=3, d=4))  # Output: 10

Keyword-Only Parameters

Keyword-only parameters are specified using a * in the function signature. Parameters after the * must be provided as keyword arguments.

def f(a, b, *, c, d):
    return a + b + c + d

# Calling the function
print(f(1, 2, c=3, d=4))  # Output: 10

Combining Different Types of Parameters

Python allows you to combine different types of parameters in a single function. The order of parameters should be: positional-only, positional or keyword, keyword-only.

def example(pos_only1, pos_only2, /, standard1, standard2, *, kw_only1, kw_only2):
    print(pos_only1, pos_only2, standard1, standard2, kw_only1, kw_only2)

# Calling the function
example(1, 2, 3, 4, kw_only1=5, kw_only2=6)
# Output: 1 2 3 4 5 6