Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: default value of function as a function argument

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading