[SOLVED] Python: default value of function as a function argument

Issue

Suppose I have the function:

def myF(a, b):
    return a*b-2*b

and let’s say that I want a default value for b to be a-1.

If I write:

def myF(a, b=a-1):
    return a*b-2*b

I get the error message:

NameError: name 'a' is not defined

I can use the code below:

def myF(a, b):
    return a*b-2*b

def myDefaultF(a):
    return myF(a, a-1)

to have myF with default value, but I don’t like it.

How can I avoid myDefaultF and have myF with default value a-1 for b without errors?

Solution

You can do the following:

def myF(a, b=None):
    if b is None:
        b = a - 1
    return a * b - 2 * b

Answered By – Selcuk

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.