Default arguments in Python
Python allows function arguments to have default values. If the function is called without the argument, the argument gets its default value.
Default Arguments:
Python has a different way of representing syntax and default values for function arguments. Default values indicate that the function argument will take that value if no argument value is passed during the function call.
The default value is assigned by using the assignment(=) operator of the form keywordname=value.
Example:1
#function definition def greet(name,msg): print("Hello",name," ",msg) #function call greet("sumit","hello how are you")
Output:
Hello sumit hello how are you
>>>
Example:2
def abc1(name="amit",msg="how are you"): print("Hello ",name," ",msg) # function call abc1() abc1("sachin") abc1("mohit","hi ")
Output:
Hello amit how are you
Hello sachin how are you
Hello mohit hi
>>>
Example:3
#function definition def greet(name, msg = "Good morning!"): print("Hello",name + ', ' + msg) # function call greet("amit") greet("sumit","How do you do?")
Output:
Hello amit, Good morning!
Hello sumit, How do you do?
>>>
In this function, the parameter name does not have a default value and is required (mandatory) during a call.
On the other hand, the parameter msg has a default value of “Good morning!”. So, it is optional during a call. If a value is provided, it will overwrite the default value.
Any number of arguments in a function can have a default value. But once we have a default argument, all the arguments to its right must also have default values. (i.e. the arguments without default values have to be given first and then the arguments with the default values are given).
This means to say, non-default arguments cannot follow default arguments. For example, if we had defined the function header above as:
def greet(msg = “Good morning!”, name):
We would get an error as:
SyntaxError: non-default argument follows default argument
Example:4
#function definition def cal(n1=10,n2=20,n3=30,n4=40): s=n1+n2+n3+n4 print("Sum = ",s) #function calling cal() cal(1) cal(1,2) cal(1,2,3) cal(1,2,3,4)
Output:
Sum = 100
Sum = 91
Sum = 73
Sum = 46
Sum = 10
>>>