Keyword Arguments in Python

In the previous article we looked at the usage of default arguments ..now we will look at what is the purpose behind the utilization of keyword arguments in Python. The arguments we have discussed so far, they were either default or positional arguments. Let us understand positional and keyword arguments with the help of an example.

def printItem(id,name,price):
    print(f "Id is {id}")
    print(f "Name is {name} ")
    print(f "Price is {price} ")

printItem(101,"abc", 100)
print()
printItem(id=102,name="xyz", price=200)

So, we have a function printItem() that accepts three parameters/arguments, in the main body of the code(outside of the function), the values passed are positional as they are given to the function in the same order as the initial function variables were written in.

Working with Keyword Arguments Python

Here is an example program to show that the argument values can be passed in any order.

def printItem(id,name,price):
    print(f "Id is {id}")
    print(f "Name is {name} ")
    print(f "Price is {price} ")

printItem(name="abc", price=100,id=102)
Output:
Id is 102
Name is abc 
Price is 100 

In the above program, the code swaps the positions of the two different functions along with their value, but the compiler can still proceed with the execution of code without errors. There is no requirement in keyword argument to get the exact order right.

In the next article, we will look at Variable Length arguments and their usage in Python.

Leave a Comment