How to set default argument for function in Python

In this tutorial, we will learn how to set a default argument for any function in Python.

In Python, we can call a function without any argument. This function will then get its default value while printing the output. But, for that to happen, we have to set a default value for the function.

We will see how to do that with an example.

Setting a default argument for a function in Python

Let us take a function name().

def name(firstname, lastname = "Gupta", Gender = "boy"):
    print(firstname, lastname, "is a good", Gender)


name("Rohan")

So, here we have set a default argument for the parameters lastname and Gender.  We can see that for setting a default argument, we have to use = operator.

While printing the output, the user has to define only the required parameter i.e in this case, firstname, whereas the other two parameters are optional.

Output:

 Rohan Gupta is a good boy.

Here, we see that even though we have not provided any argument for lastname and Gender, they have used the pre-specified or default values while printing the output.

Also, as I said that the parameters lastname and Gender are optional, if we pass an argument for those parameters, it will overwrite the default value and the new argument values will be used for printing the output.

Let us see,

def name(firstname, lastname = "Gupta", Gender = "boy"):
    print(firstname, lastname, "is a good", Gender)


name("Rohan", "Sharma")

Output:

Rohan Sharma is a good boy

Hence, we see that the new argument value has been used instead of the default one.

But, if we do not set a default argument for a parameter and call the function without any arguments, it will give an error.

def name(firstname, lastname = "Gupta", Gender = "boy"):
    print(firstname, lastname, "is a good", Gender)


name()

Output:

name()
TypeError: name() missing 1 required positional argument: 'firstname'

We can clearly see that function name should have atleast one argument passed to get the correcr output.

Also read:

Leave a Reply

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