Introduction to Python
Programming Cycle of Python
Varibles and Datatypes in Python
Input and Output in Python
Operators in Python
Precedence of Operators in Python
Typecasting in Python
If Else in Python
Loops in Python
Break, Continue and Pass in Python
Functions in Python
Default Arguments and Keyword Arguments in Python
Strings in python
Lists in Python
Tuple in Python
Dictionary in Python
Sets in Python
List Comprehension in Python
Unpacking Sequences in Python
Higher Order Functions in Python
Lambda Functions in Python
Sieve of Eratosthenes Algorithm in Python
Linear Search in Python
Binary Search in Python
Selection Sort in Python
Bubble Sort in Python
Insertion Sort in Python
Merge Sort in Python
Default Arguments and Keyword Arguments in Python
In python, there are two types of arguments - default arguments and keyword arguments.
- Default Arguments
- Keyword Arguments
Jump to specific sections
Default Arguments
In default arguments, we can set a default value for an argument. For example- salary=30000.
Then if we do not pass the value of salary during function call, then by default salary will
take the value 30000. However if the value of salary is passed during function call, then it
will use the passed value and not the default value. We can set default values for arguments during
function declaration. Consider the following code -
def employee_details(name,age,city,salary=30000):
print("Name of employee -> ",name)
print("Age -> ",age)
print("Employee lives in city -> ",city)
print("Salary -> ",salary)
employee_details("Aditi Jain",21, "Delhi")
print()
employee_details("Devanshi Sharma",22, "Delhi",40000)
Output
Name of employee -> Aditi Jain Age -> 21 Employee lives in city -> Delhi Salary -> 30000 Name of employee -> Devanshi Sharma Age -> 22 Employee lives in city -> Delhi Salary -> 40000
Keyword Arguments
Keyword Arguments are used to pass values to a function in any order. Consider the employee
_details(name, age, city, salary) function, while calling the function, we need to first pass
the name, then age, then city, and then the salary of the employee. If we alter the order of
the arguments, it will cause problems. Consider the code below.
def employee_details(name,age,city,salary):
print("Name of employee -> ",name)
print("Age -> ",age)
print("Employee lives in city -> ",city)
print("Salary -> ",salary)
employee_details(21, "Delhi", "Aditi Jain",30000)
Output
Name of employee -> 21 Age -> Delhi Employee lives in city -> Aditi Jain Salary -> 30000
As we can see, the output is meaningless. The solution is to use keyword arguments. While passing
arguments we will write the name of the argument as well as the value like this -
employee_details(age=21,city="Delhi",name="Aditi Jain",salary=30000)
Output
Name of employee -> Aditi Jain Age -> 21 Employee lives in city -> Delhi Salary -> 30000