Python Function Arguments and Parameters

Learn Python Function Arguments and Parameters with practical examples, explanations, best practices, and real-world coding techniques.

Python function arguments determine how data is passed into a function when it is called. Understanding arguments is essential for creating reusable functions with clear and predictable interfaces. Python provides several ways to pass values, including positional arguments, keyword arguments, default arguments, variable-length positional arguments, variable-length keyword arguments, and argument unpacking.

A function parameter is the variable defined in the function declaration, while an argument is the actual value supplied during the function call. Knowing the difference becomes especially important when functions have multiple inputs or when you start designing reusable APIs.

Good argument design makes functions easier to read, test, reuse, and maintain. Instead of accepting arbitrary values without a clear contract, a well-designed function communicates what it needs and how callers should provide that information.

Parameters vs Arguments

The easiest way to understand the terminology is to look at a simple function:

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


greet("Abhinash")

Here, name is the parameter. The value "Abhinash" passed during the function call is the argument.

Parameters describe what a function expects. Arguments provide the actual values at runtime.

Positional Arguments

Positional arguments are matched to function parameters according to their order. The first argument is assigned to the first parameter, the second argument to the second parameter, and so on.

def introduce(name, role, experience):
    print(f"Name: {name}")
    print(f"Role: {role}")
    print(f"Experience: {experience}")


introduce(
    "Abhinash",
    "Software Engineer",
    3
)

Positional arguments are concise and natural when the function has only a few parameters and their order is obvious.

However, positional arguments become less readable when several parameters have similar types. Accidentally swapping two values may also produce incorrect behavior that Python cannot detect if both values are valid for their respective parameters.

Keyword Arguments

Keyword arguments explicitly identify the parameter receiving each value. This makes function calls easier to read and reduces confusion when several parameters are involved.

def create_user(name, role, active):
    return {
        "name": name,
        "role": role,
        "active": active
    }


user = create_user(
    name="Abhinash",
    role="Developer",
    active=True
)

print(user)

Keyword arguments are especially useful when a function has optional settings or multiple parameters whose meanings are not obvious from the values alone.

Mixing Positional and Keyword Arguments

Python allows positional arguments and keyword arguments to be used in the same function call, but positional arguments must appear before keyword arguments.

def create_account(username, role, active=True):
    return {
        "username": username,
        "role": role,
        "active": active
    }


account = create_account(
    "abhinash",
    role="developer",
    active=True
)

print(account)

Reversing the order can result in a SyntaxError. Keeping the argument style consistent often makes a function call easier to scan.

Default Arguments

A function parameter can have a default value. If the caller does not provide that argument, Python uses the default value.

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


print(greet("Abhinash"))
print(greet("Abhinash", "Welcome"))

Default arguments are useful when a function has an optional setting with a sensible standard value. They can simplify callers because common use cases do not need to provide every possible option.

The Mutable Default Argument Trap

One of the most important Python function-argument mistakes involves using a mutable object such as a list or dictionary as a default parameter.

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


print(add_item("Python"))
print(add_item("C#"))

The default list is created once when the function is defined, not as a new list for every call. As a result, modifications can persist between calls.

The usual pattern is to use None as the default and create the list inside the function.

def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items


print(add_item("Python"))
print(add_item("C#"))

Required and Optional Arguments

A function can combine required parameters with optional parameters that have default values.

def calculate_total(price, quantity, discount=0):
    subtotal = price * quantity
    return subtotal - discount


print(calculate_total(100, 2))
print(calculate_total(100, 2, 20))

Here, price and quantity are required, while discount is optional.

Python requires parameters without defaults to be placed before parameters that have defaults in a normal function signature.

Arbitrary Positional Arguments with *args

Sometimes a function needs to accept a variable number of positional arguments. Python provides the *args convention for this purpose.

def calculate_sum(*numbers):
    return sum(numbers)


print(calculate_sum(10, 20))
print(calculate_sum(10, 20, 30))
print(calculate_sum(1, 2, 3, 4, 5))

Inside the function, numbers is a tuple containing all additional positional arguments.

def show_values(*values):
    print(type(values))
    print(values)


show_values("Python", "C#", "Java")

The name args itself is not special. The * syntax is what tells Python to collect additional positional arguments.

Arbitrary Keyword Arguments with **kwargs

The **kwargs convention allows a function to accept a variable number of keyword arguments. Inside the function, those arguments are available as a dictionary.

def create_profile(**details):
    return details


profile = create_profile(
    name="Abhinash",
    role="Developer",
    experience=3
)

print(profile)

Like args, the name kwargs is only a common convention. The double-asterisk syntax is what collects extra keyword arguments.

Using *args and **kwargs Together

A function can accept both variable positional and keyword arguments when the API genuinely needs that flexibility.

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


describe(
    "Python",
    "C#",
    level="beginner",
    published=True
)

This pattern is common in decorators, wrappers, adapters, and framework code. For normal business functions, an explicit parameter list is often easier for developers to understand.

Argument Unpacking with *

The * operator is also used when calling a function to unpack an iterable into positional arguments.

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


numbers = [10, 20, 30]

result = add(*numbers)

print(result)

The list is unpacked so that its three elements are passed as separate positional arguments to the function.

The number of unpacked values still needs to match the function's accepted positional arguments unless the function has variable positional parameters.

Keyword Argument Unpacking with **

The double-asterisk operator can unpack a dictionary into keyword arguments when calling a function.

def create_user(name, role, active):
    return {
        "name": name,
        "role": role,
        "active": active
    }


data = {
    "name": "Abhinash",
    "role": "Developer",
    "active": True
}

user = create_user(**data)

print(user)

The dictionary keys must correspond to accepted parameter names. This technique is especially useful when data is already stored in a mapping and needs to be passed into a function.

Keyword-Only Arguments

Python allows you to require certain arguments to be passed by name. Parameters placed after * in a function definition are keyword-only parameters.

def create_connection(host, port, *, timeout=30):
    print(host)
    print(port)
    print(timeout)


create_connection(
    "localhost",
    5432,
    timeout=10
)

Here, host and port may be supplied positionally, but timeout must be provided using its parameter name.

Keyword-only arguments are useful when a parameter represents an option or configuration value where explicit naming improves readability.

Positional-Only Arguments

Python also allows function authors to indicate that certain parameters must be supplied positionally. A slash / marks the end of positional-only parameters.

def calculate_area(width, height, /):
    return width * height


print(calculate_area(10, 20))

The parameters before / cannot be supplied by keyword. Positional-only parameters are useful for designing stable function interfaces and controlling how callers refer to implementation details.

Combining Positional-Only and Keyword-Only Parameters

More advanced function signatures can use both / and * to clearly define how different arguments must be passed.

def request(method, url, /, *, timeout=30, retry=False):
    return {
        "method": method,
        "url": url,
        "timeout": timeout,
        "retry": retry
    }


result = request(
    "GET",
    "/users",
    timeout=10,
    retry=True
)

print(result)

This gives the function a clear API: the main request identity is positional, while optional configuration is explicitly named.

Argument Ordering Rules

Python function signatures follow specific rules about how parameters can be arranged. Understanding these rules prevents syntax errors and makes function declarations easier to design.

Parameter Type Example Meaning
Positional-only x, / Must be passed positionally
Normal x Can normally be positional or keyword
Default x=10 Uses a default when omitted
Variable positional *args Collects additional positional arguments
Keyword-only *, timeout Must be supplied by name
Variable keyword **kwargs Collects additional keyword arguments

Defaulted parameters normally follow required parameters of the same category. Understanding this structure helps you create valid and readable function signatures.

Argument Unpacking in Loops and Function Pipelines

Argument unpacking becomes especially useful when data already exists in a collection. Instead of manually extracting each element, Python can pass the collection directly into a compatible function.

def calculate_total(price, quantity):
    return price * quantity


orders = [
    (19.99, 2),
    (29.99, 3),
    (9.99, 5)
]

for order in orders:
    total = calculate_total(*order)
    print(total)

This pattern is useful when records are represented as tuples or other iterables whose element order matches a function's parameters.

Functions Accepting Dictionaries

Functions can also receive a dictionary as a normal argument. This is different from using ** unpacking because the entire dictionary is passed as one value.

def display_user(user):
    print(user["name"])
    print(user["role"])


user = {
    "name": "Abhinash",
    "role": "Developer"
}

display_user(user)

Passing a structured object as one argument can sometimes be cleaner than adding many individual parameters, especially when the values naturally belong to one domain concept.

Argument Passing and Object Mutability

Python passes object references by assignment. This means a function receives access to the object represented by an argument, and if that object is mutable, the function may modify the same object that the caller holds.

def add_skill(skills):
    skills.append("Python")


skills = ["C#", "Angular"]

add_skill(skills)

print(skills)

The function changes the existing list. Understanding this behavior is important when designing functions because callers may or may not expect an argument to be modified.

Immutable objects such as strings and tuples cannot be modified in place. Operations that appear to change them instead create new objects and assign them to a variable.

Designing Clear Function Arguments

A function's arguments form part of its public interface. A function becomes easier to use when its parameters have meaningful names, reasonable defaults, predictable types, and a clear relationship to the operation being performed.

Avoid creating functions with a long list of unrelated parameters. If several values always travel together, consider representing them as a dictionary, tuple, dataclass, or another domain-specific object.

def create_report(
    title,
    data,
    *,
    include_summary=True,
    format="html"
):
    # Report generation logic
    pass

In this example, title and data represent the primary inputs, while include_summary and format are named configuration options.

Common Argument Errors

Python provides clear errors when a function call does not match its signature. Understanding common argument errors makes debugging much faster.

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


# Too few arguments
# add(10)

# Too many arguments
# add(10, 20, 30)

# Unexpected keyword
# add(a=10, c=20)

Common errors include missing required arguments, supplying too many positional arguments, passing an unexpected keyword, and providing the same parameter more than once.

Practical Example: Flexible Logging Function

Variable arguments can be useful when building a small logging or formatting helper that should accept a flexible number of values.

def log_message(*messages, level="INFO"):
    text = " | ".join(str(message) for message in messages)
    print(f"[{level}] {text}")


log_message("Application started")
log_message("User", 101, "logged in", level="SUCCESS")
log_message("Database", "connection failed", level="ERROR")

The function combines *messages for flexible positional input with a keyword-only configuration argument. This is a useful example of choosing argument styles based on their purpose.

Practical Example: Configuration Options

Keyword-only parameters work particularly well for configuration because they force important options to be named explicitly.

def fetch_users(
    endpoint,
    *,
    timeout=30,
    retry=False,
    page_size=50
):
    print(f"Endpoint: {endpoint}")
    print(f"Timeout: {timeout}")
    print(f"Retry: {retry}")
    print(f"Page size: {page_size}")


fetch_users(
    "/api/users",
    timeout=10,
    retry=True
)

A caller can immediately see what each optional argument controls. This becomes valuable as APIs grow and configuration options become more numerous.

Common Mistakes with Function Arguments

Swapping positional arguments

Multiple positional values with similar types can be accidentally reversed. Use keyword arguments when explicit naming improves clarity.

Using mutable default values

Lists and dictionaries used as defaults can retain state across calls. Prefer None and initialize the object inside the function.

Overusing *args and **kwargs

Flexible arguments are useful when flexibility is part of the design. Otherwise, explicit parameters provide a clearer function contract.

Passing too many unrelated values

A large parameter list can indicate that the function has too many responsibilities or that related data should be grouped into a dedicated structure.

Unintended mutation

Functions receiving mutable objects can modify those objects directly. Make mutation intentional and document important side effects.

Ignoring argument names

Poorly named parameters make APIs harder to understand. Use names that describe the role of each value rather than generic names such as x or data.

Python Function Argument Patterns

Pattern Example When to Use
Positional add(10, 20) Simple calls where order is obvious
Keyword create(name="A") Improve readability and explicitness
Default timeout=30 Provide sensible optional behavior
*args def add(*numbers) Accept variable positional values
Keyword-only *, timeout=30 Make options explicit by name
**kwargs def create(**details) Accept variable keyword values

Best Practices for Python Function Arguments

  • Use descriptive parameter names that clearly communicate what each argument represents.
  • Prefer positional arguments when the order and meaning are obvious, and keyword arguments when explicit naming improves readability.
  • Use default values for genuinely optional behavior with sensible defaults.
  • Never use mutable objects such as lists or dictionaries as defaults unless their shared lifetime is explicitly intended.
  • Use *args and **kwargs when variable argument counts are a genuine requirement.
  • Use keyword-only parameters for optional configuration that benefits from explicit naming.
  • Use argument unpacking when data already exists in a compatible iterable or dictionary.
  • Be intentional when functions modify mutable arguments passed by the caller.
  • Avoid unnecessarily large parameter lists; group closely related data into an appropriate structure when necessary.
  • Keep the function signature predictable and aligned with the function's responsibility.

Why Python Function Arguments Matter

Function arguments form the communication layer between a function and the code that uses it. A function may have excellent internal logic, but a confusing parameter interface can still make the function difficult to use and maintain.

Python gives developers a flexible argument system that supports simple positional calls as well as expressive keyword arguments, default values, variable-length arguments, positional-only parameters, keyword-only parameters, and unpacking.

The important skill is not memorizing every syntax variation. It is choosing the simplest argument design that clearly communicates what the function needs. When callers can immediately understand which values are required, which are optional, and how each option changes behavior, your functions become easier to reuse and safer to maintain.

Code Examples

Positional and Keyword Arguments

python
def create_user(name, role, active=True):
    return {
        "name": name,
        "role": role,
        "active": active
    }

user = create_user(
    "Abhinash",
    role="Developer",
    active=True
)

print(user)
    

Safe Default Argument

python
def add_item(item, items=None):
    if items is None:
        items = []

    items.append(item)
    return items

print(add_item("Python"))
print(add_item("C#"))
    

Variable Positional Arguments

python
def calculate_sum(*numbers):
    return sum(numbers)

print(calculate_sum(10, 20))
print(calculate_sum(10, 20, 30, 40))
    

Keyword-Only Arguments

python
def fetch_users(
    endpoint,
    *,
    timeout=30,
    retry=False,
    page_size=50
):
    print(f"Endpoint: {endpoint}")
    print(f"Timeout: {timeout}")
    print(f"Retry: {retry}")
    print(f"Page size: {page_size}")

fetch_users(
    "/api/users",
    timeout=10,
    retry=True
)
    

Argument Unpacking

python
def calculate_total(price, quantity):
    return price * quantity

order = (19.99, 3)

total = calculate_total(*order)

print(total)
    

Pro Tip

Treat function arguments as part of your API design. Keep required inputs explicit, use keyword arguments for important options, avoid mutable defaults, and only introduce *args or **kwargs when the function genuinely needs variable inputs.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.