Skip to content
Advertisement

Python function make parameter mandatory if another parameter is passed

I have a function in Python as

def myfunc(a, b=None, c=None):
    my code here

Is there a way to ensure that if the user passes the value of the parameter b it is necessary to pass the parameter c to myfunc?

Advertisement

Answer

You can write a simple if condition in your function. See the code below:

def myfunc(a, b=None, c=None):
    if c is not None and b is None:
        raise ValueError("Value of b must be passed if value of c is passed")
    your code here
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement