Functions Again

Arguments
Consider our previous function that was created that takes two parameters, num1 and num2.

So, while calling the function we need to pass the same number of parameters i.e., if the function definition has two parameters, we need to pass two values, if the function definition has three parameters, we need to pass three values.

Let’s see what will happen in case the parameter’s count are not matching:

In the last sentence, we are calling addition function with only one parameter. We will get error as below:

It clearly says that one parameter is missing and the parameter is num2.

Now, let’s try calling the function by giving more number of parameters as shown below.

In the last sentence, we are calling the addition function with 3 parameters but the definition is expecting only two parameters.

This will again throw an error as shown below:

The error message clearly says that the function expects 2 arguments however 3 parameters were given.

Default Parameters

Now, there could be a scenario where we need to pass some default values to the parameters when there are no values passed.

Let’s discuss with an example:

Let’s reuse the same addition function that we created earlier.

Now, while calling the function, we need to pass two parameters. If we don’t pass the required parameters, it will throw an error as discussed earlier.

To avoid these type of issues, we can use default parameters where we can specify default value to the parameters.

Let’s understand with our same addition function, but observe the parameters now in the definition.

If you observe the parameters, we have passed the default values to the parameters.

The default value for num1 is 1 and num2 is 2.

Now, let’s try calling the function by not passing any parameter, or by just passing one parameter as shown below.

We have called the addition function in three different ways like by not passing any parameters, by passing only one parameter and by passing the required parameters.

The output is:

The first addition has taken the default value for the parameters and did an addition for 1 and 2 (as there was not values passed) and thus, the output is 3.

Please note that there is no error now.

Similarly, in the next statement, we have called addition function with only one parameter value i.e., 4.

Now addition function has replaced num1 with 4 and as num2 doesn’t have any value, it has used the default value i.e., 2 and the addition of 4 and 2 is 6 and thus, the output.

Please note that there is no error now either.

In the next statement, we have called addition function with both the parameters i.e., 4 and 7

Now addition function has replaced num1 with 4 and num2 as 6 and the addition of 4 and 6 is 10 and thus, the output.

We have learnt enough of functions now. I will come back to you with another post on a different topic in Python.

Leave a comment

Design a site like this with WordPress.com
Get started