Keyword-Only Arguments in Python

Welcome back, guys. In this post, we will learn about the concept of Keyword-only arguments in Python.

Keyword arguments, a method of passing actual arguments to the user-defined function. We know that python uses four different ways of passing arguments to the function. They are position, keyword, default and variable length. Positional arguments need to pass the argument in a sequence. Therefore, the keyword argument is preferred to avoid any error.

 Also See: How to find common elements from two tuples

In the keyword argument method, we use a keyword to pass the parameters to the function.

How to use keyword arguments in Python

To understand the keyword method of passing arguments, we also have to understand the positional method of passing arguments.

Let’s understand with below example.

def keyword(Q1,Q3):
    print(f"Q1={Q1},Q3={Q3}")
    QuartileD=(Q3-Q1)/2
    print(QuartileD)

The above function keyword takes two arguments  Q1 and Q3. When we use the positional argument method and swap the position of values answer also changes.

if __name__ == '__main__':
    keyword(30,65)
    keyword(65,30)

Output:

Q1=30,Q3=65
17.5
Q1=65,Q3=30
-17.5

To overcome this, the keyword argument method is used in which values are passed with the help of a keyword.

if __name__ == '__main__':
    keyword(Q1=14,Q3=27)
    keyword(Q3=27,Q1=14)

In the above code, we can see that Q1 and Q3 are used to pass the arguments as Q1=14  and Q3=27 and their positions are also changed. Changing in the position of Q1 and Q3 does not affect the output in any way.

Output:

Q1=14,Q3=27
6.5
Q1=14,Q3=27
6.5

In this way, we can use the keyword to pass the arguments. That’s all about the keyword-only argument in Python. If you have any doubts relating to the argument passing then please comment below any time. We will help you to clarify your doubts.

Leave a Reply

Your email address will not be published. Required fields are marked *