Python Default Parameters (With Examples)

Python Default Parameters: In this tutorial, we will learn about the default parameters and their usage with the help of examples. By Ankit Rai Last updated : December 30, 2023

Python Default Parameters

A default parameter is a value provided in a function declaration that is automatically assigned by the compiler if the caller of the function doesn't provide a value for the parameter with the default value.

Syntax

The syntax of the Python default parameters is:

def function_name(parameter = value):
    body

Python Default Parameters Example

Following is a simple Python example to demonstrate the use of default parameters. We don't have to write 3 Multiply functions, only one function works by using default values for 3rd and 4th parameters.

# A function with default arguments, it can be called with
# 2 arguments or 3 arguments or 4 arguments .

def Multiply(num1, num2, num3=5, num4=10):
    return num1 * num2 * num3 * num4

# Main code
print(Multiply(2, 3))
print(Multiply(2, 3, 4))
print(Multiply(2, 3, 4, 6))

Output

300
240
144

Pointe To Remember

  • Default parameters are different from constant parameters as constant parameters can't be changed whereas default parameters can be overwritten if required.
  • Default parameters are overwritten when the calling function provides values for them. For example, calling of function Multiply(2, 3, 4, 6) overwrites the value of num3 and num4 to 4 and 6 respectively.
  • During calling of function, arguments from calling a function to parameters of the called function are copied from left to right. Therefore, Multiply(2, 3, 4) will assign 2, 3 and 4 to num1, num2, and num3. Therefore, the default value is used for num4 only.

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.