Default Argument | How Do I Define A Function With Optional Arguments?

In this post, we will learn How to define a function with default optional arguments which we can do by providing default values in the arguments in the function definition only see the example of the same have a look at the example given below.

Default Function

Function With Default Arguments

As we know there could be a condition when we do not know the number of arguments that could be passed in a function but we have to execute the same function for the calculation of the value we want to get on the basis of some default values which could be anything we provided before so here is the code to understand how we can define the values to the function and it will be executed on those values only.

def my_function(a, b=0, c=1):
    result = a + b + c
    return result
# Possible Function calls
my_function(5)       # Returns 6
my_function(5, 2)    # Returns 8
my_function(5, 2, 3) # Returns 10

Here we can see how the function provided here named my function has three arguments a, b, and c where we have already assigned some value to the argument a, b, and c which will be automatically assigned to those variables during calling which we might be needed for some calculation in the function we are working on.

In the above case, we had called the same function in three different ways and in each way had given a different number of arguments as discussed before, and the properties of the functions in the conditions when we did not give all three arguments it is going to take its default values which we had already assigned to the function as per our requirements.

Here we can see each time the result is different as the values of the parameter keep on changing as we make changes in the number of arguments of the functions as the numbers get changed.

These types of functions are used when we have the uncertainty of the number of variables so that time we need such functions where we can such functions where we can provide the default values if the number or the arguments is not provided.

 

 

To learn more about How Do I Define A Function With Optional Arguments visit: by stack overflow.

To learn more about python solutions to different python problems and tutorials for the concepts we need to know to work on python programming along with different ways to solve any generally asked problems: How To Pass-Variables From A Java & Python Client To A Linux/Ubuntu Server Which Is Running C?.

Leave a Comment

%d bloggers like this: