Simple Guide to Function Arguments in Python
Understanding how to use function arguments effectively is essential for writing flexible and reusable code in Python. Article covers positional, keyword, default, and variable-length arguments.
Simple Guide to Function Arguments
I tried to draw the blueprint for building clean, reliable, and well-structured functions in the previous article. In this one, I’ll continue by providing you with a simple guide to different types of function arguments in Python:
Positional Arguments
Keyword Arguments
Default Arguments
Variable-Length Arguments (
*args
,**kwargs
)
Follow me on LinkedIn 🚀
Positional Arguments
When the function’s parameters are few and their order is obvious and consistent, we use positional arguments. These are the simplest form of arguments and as the name suggests, their values are assigned to parameters based on their position in the function call.
Let’s consider the following function - calculate_force(…)
def calculate_force(mass: float, acceleration: float) -> float:
"""
Calculate the force using Newton's Second Law of Motion.
Args:
mass (float): The mass of the object in kilograms.
acceleration (float): The acceleration of the object in meters per second squared.
Returns:
float: The force in Newtons.
"""
return mass * acceleration
force = calculate_force(10, 9.8)
print(f"Force: {force} N")
Keyword Arguments
Keyword arguments are often used when the function has many parameters, optional parameters, or when the order of parameters might be confusing. They are passed to the function by explicitly naming each parameter and providing a value. This way we can specify arguments in any order.
The following function, calculate_gravitational_force(…)
, demonstrates the use of keyword arguments.
def calculate_gravitational_force(
mass1: float, mass2: float, distance: float
) -> float:
"""
Calculate the gravitational force between two masses.
Args:
mass1 (float): The mass of the first object in kilograms.
mass2 (float): The mass of the second object in kilograms.
distance (float): The distance between the two objects in meters.
Returns:
float: The gravitational force in Newtons.
"""
G = 6.67430e-11 # Gravitational constant in m^3 kg^-1 s^-2
return G * (mass1 * mass2) / distance**2
force = calculate_gravitational_force(
distance=3.84e8,
mass1=5.97e24,
mass2=7.35e22
)
print(f"Gravitational Force: {force} N")
Default Arguments
As the name suggests, we can specify a default value for function parameters and make them optional in the function call.
Let’s learn about default arguments with the following function: calculate_potential_energy(…)
def calculate_potential_energy(
mass: float, height: float, gravity: float = 9.8
) -> float:
"""
Calculate the potential energy of an object.
Args:
mass (float): The mass of the object in kilograms.
height (float): The height of the object in meters.
gravity (float, optional): The acceleration due to gravity in meters per second squared. Defaults to 9.8.
Returns:
float: The potential energy in joules.
"""
return mass * height * gravity
pe = calculate_potential_energy(10, 20)
print(f"Potential Energy: {pe} J")
As we can see, I omitted the gravity parameter from the function call as it defaults to 9.8. Of course, we can add it if the function is called for another planet 🪐 - calculate_potential_energy(10, 20, 10)
Variable-Length Arguments (*args
and **kwargs
)
*args
Sometimes the function needs to accept a variable number of positional arguments. That’s when we use *args
which inside the function translates to a tuple of all the positional arguments. Here’s a calculate_moments_of_inertia(…)
to demonstrate the use of *args
.
def calculate_moments_of_inertia(*radii: float, mass: float) -> float:
"""
Calculate the moments of inertia for multiple radii.
Args:
*radii (float): A variable number of radii in meters.
mass (float): The mass of the object in kilograms.
Returns:
float: The sum of moments of inertia.
"""
return sum(0.5 * mass * r**2 for r in radii)
inertia = calculate_moments_of_inertia(0.1, 0.2, 0.3, mass=10)
print(f"Total Moments of Inertia: {inertia} kg·m^2")
We passed 3 positional arguments in the example, but we could pass 12, 13 or any number.
**kwargs
We’ve seen how to accept a variable number of positional arguments, what if we need to pass keyword arguments to the function? That’s when we use **kwargs
syntax.
def describe_experiment(**details: dict) -> None:
"""
Describe the details of an experiment.
Args:
**details (dict): A variable number of keyword arguments describing the experiment details.
Returns:
None
"""
for key, value in details.items():
print(f"{key}: {value}")
describe_experiment(
name="Free Fall", duration="10s", location="Lab A", temperature="300K"
)
# Output
name: Free Fall
duration: 10s
location: Lab A
temperature: 300K
Combining *args
and **kwargs
Now let’s build a function with positional arguments, *args, and **kwargs -
def summarize_experiment(
experiment_name: str, *readings: float, **details: dict
) -> None:
"""
Summarize the results of an experiment.
Args:
experiment_name (str): The name of the experiment.
*readings (float): A variable number of readings from the experiment.
**details (dict): Additional details about the experiment.
Returns:
None
"""
print(f"Experiment: {experiment_name}")
print("Readings:")
for reading in readings:
print(reading)
print("Details:")
for key, value in details.items():
print(f"{key}: {value}")
summarize_experiment(
"Free Fall", 9.8, 9.7, 9.9, duration="10s", location="Lab A"
)
Key Considerations
Clarity and Readability: Always prioritize code readability. Use keyword arguments to make function calls clear and explicit.
Order Matters: Remember the order of arguments in a function definition:
Positional arguments
*args
Keyword arguments
**kwargs
Avoid Overcomplication: Overusing
*args
and**kwargs
can make the code harder to understand and debug, so be careful when using them.Documentation: Always document (in Docstrings) functions well, especially when using
*args
and**kwargs
, to explain what kinds of arguments are expected.
I hope you liked the article. If you have questions or need further clarification, leave a comment below or reach out directly.
✅ Thank you for reading my article on SA Space! I welcome any questions, comments, or suggestions you may have.
Keep Knowledge Flowing by following me for more content on Solutions Architecture, System Design, Data Engineering, Business Analysis, and more. Your engagement is appreciated. 🚀
🔔 You can also follow my work on LinkedIn | Substack | Threads | X
I think the examples would look better perhaps in color. Other than that Good job!
My next posts here and elsewhere about forGL must include colored samples
to help show details.
@Substack code block feature
needs a way to mark colors or something else to have syntax colored code.
I was thinking of doing .jpg screen shots.
But there is no easy way for lazy Software Developers to copy / paste from .jpg so not as convenient as possible.
Here is a link to online pdf that anyone may download. Dangerously Advanced Python
https://mike.verdone.ca/media/Dangerously%20Advanced%20Python.pdf