Search code examples
pythonfunctiondefault-value

What is the benefit of using assigning a default value to a parameter in a function in python


Python allows us to set a value to a parameter by default. The following example is taken from A smarter way to learn python by Mark Myers.

def calc_tax(sales_total,tax_rate=0.04):
    print(sales_total * tax_rate)

I don't understand what is its use when we can do this:

def calc_tax(sales_total):
    print(sales_total*0.04)

Solution

  • It's because when doing:

    def calc_tax(sales_total,tax_rate=0.04):
        print(sales_total * tax_rate)
    

    You can do:

    calc_tax(100)
    

    Then here tax_rate is an argument that's assigned to a default value so can change it by:

    calc_tax(any thing here,any thing here)
    

    OR:

    calc_tax(any thing here,tax_rate=any thing here)
    

    So in the other-hand, this code:

    def calc_tax(sales_total):
        print(sales_total*0.04)
    

    Is is only able to do:

    calc_tax(any thing here)
    

    Because there is no second argument