Loop Control Statements in C Introduction to HTML How to use the Github API The image tag, anchor tag and the button tag Ordered and Unordered Lists in HTML The division tag HTML Forms Tables in HTML Introduction to C Programming Introduction to Python Varibles and Datatypes in Python Operators in Python Typecasting in Python Input and Output in Python If Else in Python Loops in Python Break, Continue and Pass in Python Python practice section 1 Lists in Python Tuple in Python

Default Arguments and Keyword Arguments in Python

In python, there are two types of arguments - default arguments and keyword arguments.

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