[SOLVED] Is there a way to have optional arguments in a function in Python?

Issue

I have defined a function in Python which takes some arguments and plots a graph. I would like to extend this so that if certain additional optional arguments are passed into the function then it will plot another graph on the same set of axes but only if these optional arguments are passed into the function. The plotting of the data inside the function is not the issue but how would I create a function that will work if optional arguments are not passed?

For example, I would like to define a function such as below which will work even if optional_arg3 and optional_arg4 are not passed.

def function(arg1, arg2, optional_arg3, optional_arg4):

Any help would be really appreciated!

Solution

This is easy in python by providing default values for arguments. So if no value is passed, the arguments take up the default value. Eg:

def a(b, c, d=None):
    print(b, c, d)
    
a(1,2)

since I only passed b and c, d takes up the default value of None
So output:

1 2 None

Answered By – Anshumaan Mishra

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

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