Python Function Arguments Explained with Examples

In Python, functions can accept arguments that are passed when the function is called. These arguments can be required or optional.

Positional Arguments

Positional Arguments are the most common type of function arguments. When you call a function with positional arguments, the arguments are matched to the parameters of the function based on the order they are defined in the function signature.

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

# Calling the function with positional arguments
message = greet("Alice", "Hello")
print(message)  # Output: "Hello, Alice!"

Keyword Arguments

Keyword Arguments allow you to pass arguments to a function by specifying the parameter name along with the value.

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

message = greet(greeting="Hi", name="Bob")
print(message)  # Output: "Hi, Bob!"

Default Arguments

Default Arguments allow you to specify default values for parameters in a function. If a value is not provided for a parameter when the function is called, the default value is used.

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

# Calling the function without specifying the greeting
message = greet("Alice")
print(message)  # Output: "Hello, Alice!"

# Calling the function with a specified greeting
message_custom = greet("Bob", "Hi")
print(message_custom)  # Output: "Hi, Bob!"

In this example, the greet function has a default value (“Hello“) assigned to the greeting parameter.

When calling the function without providing a value for greeting, the default value is used.

If a value for greeting is provided in the function call, that value overrides the default.

*args and **kwargs Arguments

*args and **kwargs allow passing a variable number of arguments to a function.

def example(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

example(1, 2, a="apple", b="banana")

# Output:
# Positional arguments: (1, 2)
# Keyword arguments: {'a': 'apple', 'b': 'banana'}

Unpacking Arguments

Arguments can be unpacked from lists or dictionaries using * and **.

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

params = ["Alice", "Hello"]
message = greet(*params)
print(message)  # Output: "Hello, Alice!"