free geoip
6

Python Function Parameters and Arguments

In Python, functions are one of the most important building blocks of any program. They allow you to organize your…

In Python, functions are one of the most important building blocks of any program. They allow you to organize your code into reusable blocks, making it easier to read, maintain, and debug. But when you define or call a function, you often need to pass data into it — this is where parameters and arguments come in.

Understanding the difference between parameters and arguments, and how to use them properly, is essential for mastering Python functions. In this article, we’ll explore in depth what parameters and arguments are, the types of parameters in Python, how to use them effectively, and examples that make each concept clear.

Python Function Parameters and Arguments

What Are Parameters and Arguments?

Before diving deeper, let’s clarify the difference between parameters and arguments — two terms that are often used interchangeably but have distinct meanings.

  • Parameters are variables listed inside the parentheses in the function definition. They act as placeholders for the values that will be passed to the function.
  • Arguments are the actual values passed to the function when it is called.

Example:

def greet(name):  # 'name' is a parameter
    print("Hello, " + name)

greet("Alice")    # 'Alice' is an argument

In this example, name is a parameter that receives the argument "Alice" when the function is called.

Types of Function Parameters in Python

Python provides several ways to define parameters, making it one of the most flexible languages when dealing with functions. Here are the main types of parameters:

1. Positional Parameters

Positional parameters are the most common type. The order in which you pass arguments to the function matters.

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

result = add(3, 5)
print(result)

In the code above, a receives the first argument (3), and b receives the second (5).

2. Keyword Parameters

Keyword parameters allow you to specify which parameter each argument belongs to by name. This makes the order of arguments irrelevant and improves code readability.

def student_info(name, age):
    print(f"Name: {name}, Age: {age}")

student_info(age=21, name="Bob")

Even though the arguments are passed in a different order, Python understands which is which because of the keywords.

3. Default Parameters

Default parameters allow you to assign default values to parameters. If no argument is provided, the function uses the default value.

def greet(name="Guest"):
    print(f"Hello, {name}!")

greet()           # Output: Hello, Guest!
greet("Charlie")  # Output: Hello, Charlie!

This is useful when you want to make parameters optional.

4. Variable-Length Parameters (*args)

Sometimes, you don’t know in advance how many arguments will be passed to a function. Python allows you to handle such cases using *args.

def total(*numbers):
    sum = 0
    for num in numbers:
        sum += num
    return sum

print(total(1, 2, 3))
print(total(10, 20, 30, 40))

Here, *args collects all positional arguments into a tuple, allowing you to work with multiple arguments dynamically.

5. Keyword Variable-Length Parameters (**kwargs)

If you want to accept an arbitrary number of keyword arguments, you can use **kwargs. It collects keyword arguments into a dictionary.

def profile(**data):
    for key, value in data.items():
        print(f"{key}: {value}")

profile(name="Sarah", age=25, city="Jakarta")

Output:

name: Sarah
age: 25
city: Jakarta

This is especially useful when dealing with dynamic or optional configuration data.

Mixing Different Types of Parameters

You can combine different types of parameters in one function definition, but you must follow a specific order:

  1. Positional parameters
  2. *args
  3. Keyword parameters with default values
  4. **kwargs

Example:

def order(item, *extras, delivery="standard", **details):
    print(f"Item: {item}")
    print(f"Extras: {extras}")
    print(f"Delivery: {delivery}")
    print(f"Details: {details}")

order("Pizza", "Cheese", "Mushrooms", delivery="fast", address="Jakarta", phone="123456789")

Output:

Item: Pizza
Extras: ('Cheese', 'Mushrooms')
Delivery: fast
Details: {'address': 'Jakarta', 'phone': '123456789'}

This kind of flexibility is one of the reasons Python functions are so powerful.

Positional-Only and Keyword-Only Parameters (Python 3.8+)

Starting with Python 3.8, you can explicitly define whether parameters must be positional-only, keyword-only, or both. You can do this using / and * symbols in the function definition.

def greet(name, /, greeting="Hello"):
    print(f"{greeting}, {name}")

greet("Rysa")           # Works fine
# greet(name="Rysa")    # Error: name must be positional

Similarly, using * in the parameter list makes all following parameters keyword-only.

def introduce(*, name, age):
    print(f"Name: {name}, Age: {age}")

introduce(name="Ali", age=20)  # Works
# introduce("Ali", 20)         # Error: must use keyword arguments

Common Mistakes with Parameters and Arguments

  • Passing arguments in the wrong order for positional parameters.
  • Forgetting to use * or ** when unpacking arguments.
  • Using mutable default values (like lists or dictionaries) that persist across function calls.

Example of a mutable default pitfall:

def add_item(item, item_list=[]):
    item_list.append(item)
    return item_list

print(add_item("apple"))
print(add_item("banana"))  # The previous list is reused!

To fix this, always use None as the default value for mutable types:

def add_item(item, item_list=None):
    if item_list is None:
        item_list = []
    item_list.append(item)
    return item_list

Conclusion

Understanding how Python function parameters and arguments work is a crucial part of becoming an efficient Python programmer. Parameters define the interface of a function, while arguments are the data passed to it during execution. With positional, keyword, default, *args, and **kwargs parameters, Python offers tremendous flexibility in function design.

By mastering these concepts, you can write cleaner, more reusable, and more dynamic code — whether you’re building a small script or a large-scale application.

rysasahrial

Leave a Reply

Your email address will not be published. Required fields are marked *