Python

What are Python default function parameters ?

In this tutorial, we will see what are Python default function parameters and how they are useful.

Python default function parameters:

A default function parameter is used by the python compiler to assign a default value to the parameter when there is no explicit value provided by the function caller. It is the most effective way of writing code to eliminating the value errors at runtime.

In the following example, I am going to calculate the simple interest with some default parameters.

if __name__ == '__main__':

    def calculate_simple_interest(p,t=1,r=10):
        # simple interest = (p * t * r) / 100
        # Where,
        # p is the principal amount
        # t is the time in years and
        # r is the rate of interest

        # taking default interest rate, years as default parameters - 10,1 respectively
        return p * t * r / 100

    # function call with default parameter values
    interest = calculate_simple_interest(100000)
    print("Interest with default values ",interest)

    # function call with overridden parameter values
    interest = calculate_simple_interest(100000,2,4)
    print("Interest overridden parameters ",interest)

Output:

Interest with default values  10000.0
Interest overridden parameters  8000.0
On the above example default rate of interest, years as default parameters – 10,1 respectively

Points to Note:

  • Default parameters are not constants it’s mutable, that means we can change them as when we want.
  • Default parameters can be overridden when calling the function.
  • We can even change the default parameter values inside the function body.

References:

Happy Learning :)

Found a mistake or something out of date? Tell us →

Written by

chandrashekhar

Founder of onlinetutorialspoint.com. Enterprise architect with 15+ years in healthcare technology, designing and running systems on AWS and Azure. Writes about building real things with AI, local AI hardware and cloud certifications.

Keep reading

Ask a question or leave a comment