Create a Python function with optional arguments

We can set the default value to our Python function. That means if we don’t pass our argument value during calling a Python function, it will take a default value that we will define. That means, the Python function can have optional arguments that we may pass or may not, but still will not return any error.

So, in this post, I am going to tell you how to create a Python function with optional arguments.

Creating a function with optional arguments in Python is quite an easy task. Let’s see with our first exam.

Below we have created a Python function with a default argument:




def my_function(a=10):
    print(a)

my_function()

In the above code, you can see that I have assigned a value to the argument of the function. When I call the function, I haven’t passed any parameters or argument. But when we run our code, we will see the output that is given below:

10

So, we have understood that if we assign a value to the parameter during creating our function, then if we don’t pass any parameter during calling the function, it will take the assigned value to the parameter.

But if we pass the parameter value, it will change the default value of our argument just like you can see below:

my_function(55)

Output:

55

We can see that, after we pass the argument value, the default value was changed.

 

Now see another example, but this time with a Python function with multiple default parameter. Below is our python program:

def my_function(a=10, b=12):
    print(a)
    print(b)

my_function()

Output:

10
12

In our above example also, we can see that the Python function taking default argument values that we had passed during creating our function when we call it.

So in this example, we have created a Python function with two default arguments.

 

Also, read:

 

Now suppose we want to change the value of one parameter only and keep another function parameter as it is. Below is the program that will do it:

my_function(b=44)

The output will be:

10
44

So we can see that when we pass the argument value of b, it change the default value. But keep the value of other parameters of our function default as we defined.

That means, if we want to change any of the default parameters value, then we have to assign a new value to it.

If we change both of the values or both of the parameters, then we have to assign values to all the parameters of our function just like you can see below:

my_function(a=21, b=44)

 

So, in this post, we have learned how to create a Python function with default arguments and how to change the argument values that we defined during creating our function.


Leave a Reply

Your email address will not be published. Required fields are marked *