Default parameters are a powerful feature in Python that allow you to set default values for parameters in a function definition. This means that you can define a function with optional parameters that have a default value assigned to them already. When the function is called, if the caller omits providing a value for that parameter, it will automatically use the default value. In this tutorial, you will learn how to create functions with default parameters, how to use them in your code, and some best practices to keep in mind when working with default parameters in Python. Let's dive in!

Default parameters :

  • In Python when we define a function, we can assign a default value to the parameters.
  • This default value of any parameter is used in the function body in case we do not pass that argument while calling the function.
  • When we pass an argument while calling a function, this argument value is used in the function body even if the parameter has any default value.
  • the syntax of passing default values in python is as follows :

def my_function(param_1, param_2=value2, param_3=value3, ...):
  • Parameters with default values should be placed after other parameters.
  • Suppose we have three parameters with default values then, these three parameters should be the last three parameters of the function.
  • In other words, a parameter without default value cannot be placed after any parameter with default value.
  • Code sample :

# Defining function area_triangle
def area_triangle(base, height=10):
    area = 0.5 * (base * height)
    return area

b = 4
h = 20

# calling the function area_triangle without height argument
# default value of height will be used
ar = area_triangle(b)
print("The area of triangle is : ", ar)

# calling the function area_triangle with height argument
ar = area_triangle(b, h)
print("The area of triangle is : ", ar)

# Output
# The area of triangle is :  20.0

# The area of triangle is :  40.0

Prev. Tutorial : Passing arguments

Next Tutorial : Global and Local Variables