[SOLVED] How can I accept default parameter in function when 'None' or no argument is passed?

Issue

I am writing a new python class with a generic function. At one point I have a requirement as follows

def function(a=1):
    ....
    ....
    print a # here I want a to be 1 if None or nothing is passed

Eg:

  • a(None) should print 1
  • a() should print 1
  • a(2) should print 2

Is there a way to do this?

Solution

You can define a function with a default argument, later you can check for the value passed and print it:

def fun(a=1):
    a = 1 if a is None else a
    print(a)

Answered By – Strik3r

Answer Checked By – Mary Flores (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.