Arguments
What are Arguments
In Python, arguments are the values that are passed to a function when it is invoked or called. They are essential as they allow a function to receive data it can use in executing its instructions. You can send any data types such as a list, string, number, etc., as an argument to a function.
To better visualize this concept, let’s write a simple function that multiplies two numbers, with those numbers being the arguments.
In the above example, the function multiply
is called with the arguments 2 and 3, and it returns the multiplied result 6.
Positional Arguments
Positional arguments are the most common type and must be passed in the order in which they’re defined in the function.
In the example above, “John” and 22 are positional arguments. They need to be in the same order as the parameters name
and age
declared in the function greet
.
Caution
Mismatching the order of arguments with their respective function parameters can lead to logical error, or unexpected behavior of the function.
Keyword Arguments
Keyword arguments allow you to specify arguments by their names, overriding the order. They are identified by the function parameter’s name followed by an equal sign and the value you want to set.
Here, even though “John” and 22 are not in the order of parameters in function, Python knows which is which because they’re defined by keywords.
Note
You can mix positional arguments and keyword arguments in a function call. However, positional arguments must come before keyword arguments.
Arbitrary Arguments
Sometimes, you may not know beforehand how many arguments you will pass to a function. Python allows for this with arbitrary arguments or varargs. To denote this, an asterisk (*) is used before the parameter name in the function definition.
In this example, Python packs all of the arguments into a tuple that can be iterated over, which is what happening in the for loop.
Functions are a powerful tool in Python, and understanding how arguments work is integral to leveraging this power efficiently and effectively.