This lesson will be about parameters. We will learn what parameters exist, how they differ, and when to apply them.
What parameters are available
Arguments are the data passed to the function call. There are two types:
The first type is positional arguments. We pass them in the same order in which we define the function parameters:
# (text, length)
truncate('My Text', 3)
The second type is named arguments. We pass them not as regular values but as a name=value
pair. Therefore, we can write them in any order:
# We pass the arguments in a different order
truncate(length=3, text='My Text')
We can look carefully at the two examples above and notice that the two functions are identical.
Now we will discuss when we need to apply these types of arguments.
What parameters to use
The type of parameter you choose depends on who calls the function.
There are two reasons to use named arguments:
They increase readability because you can see the names at a glance
We do not need to specify all the intermediate parameters because they are unnecessary at the moment
The latter point is if the function has many optional parameters. Let us look at an example:
def f(a=1, b=2, c=None, d=4):
print(a, b, c, d)
# We only need to pass `d`, but we end up having to pass everything
f(1, 2, 3, 8)
# The named arguments allow us to pass only `d`
# We use default values for the other arguments
f(d=8)
Named arguments can be passed at the same time as positional arguments. In that case, the positional ones should go at the beginning:
# We pass only `a` as a positional argument and `d` as a named one
f(3, d=3)
In this lesson, we have limited ourselves to basic knowledge to help you read sample code with named arguments.