Python Arguments

Python Arguments

Python arguments are variables passed into a function at the point of declaration/definition. The function eventually works on the arguments to produce its result.

See example of python argument and how it used the function in the first image

image.png

Default Argument:

Default argument is the type used in functions with a default value at the point of defining such function. See example in the image below: So you can call the function without passing in the argument with a default value. The function in this case, uses the default value supplied when declaring the it.

image.png

Keyword Argument:

Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. The following calls to the above function are all valid and produce the same result.

doubleMyValue(value=3, addedValue=1)

Above is an example of keyword argument. The value of the parameter needed are provided by default. We can also swap the position in this way

doubleMyValue(addedValue=1, value=3)

However we can mix positional argument with a keyword argument, let's take a look at an example:

doubleMyValue(1, addedValue=3)

Notice the parameter in the first position is just provided without assigning value to the name of the argument. The first argument or parameter is called positional argument while the other argument is keyword argument.

The caveat here is you cannot have a keyword argument before a positional argument. It throws a syntax error i.e. doubleMyValue(value=1, 3) throws syntax error.

Arbitrary Argument

Sometimes, the number of arguments that will be passed into a function is not known from the start. Python allows us to handle this kind of situation through function calls with an arbitrary number of arguments.

In the function definition, we use an asterisk (*) before the parameter name to denote this kind of argument. Here is an example.

image.png

Note that the argument numbers can have more items than in this example.

That brings us to end of this. If you have questions please put the comment or reach out via linkedin