Home » Python

Python default parameters

Default parameters in Python: Here, we are going to learn about the default parameters in Python with example.
Submitted by Ankit Rai, on May 27, 2019

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.

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.

Code:

# 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

Key points:

1) Default parameters are different from constant parameters as constant parameters can't be changed whereas default parameters can be overwritten if required.

2) 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.

3) 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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.