Python Keyword Arguments (With Examples)

python-keyword-arguments-with-examples

Python Keyword Arguments are the arguments that you can pass through a function by specifying an argument with the parameter name.

When calling a function, sometimes it becomes difficult to pass the values in the same order you defined. You can use python keyword arguments here to get the task done.

How do you take keyword arguments in Python?

Let’s say you want to calculate the area of a rectangle. The area of a rectangle is its length multiplied by its width.

You brainstorm, think about the logic, and build a function to use whenever and wherever you need it in your program.

And it seems like this.

def area_of_rectangle(length, width):
    return length * width

Cool! you are a programmer now.

You check this function by calling it passing some value of length and width through it.

And it works absolutely as it supposed to be and you got the area of your rectangle.

def area_of_rectangle(length, width):
    return length * width
    
area = area_of_rectangle(3,7)
print(area)

Output

21

But what if you forget what was the first parameter?

Whether it was length or width?

Python keyword arguments come in handy here.

You can mention length and width as the keyword arguments and then specify their values.

Let’s have a look at this.

def area_of_rectangle(length, width):
    return length * width
    
area = area_of_rectangle(width=5,length=9)
print(area)

Output

45

Example 2 on Python Keywords Arguments

Now, let’s have look at some other examples to grip stronger on this.

You have to find the volume of a box. You made the function some time ago but didn’t remember the position of each argument.

Use the concept of python keyword argument to solve the problem.

Code

def volume_of_box(length, width, height):
    return length * width * height

volume = volume_of_box(height=2, width=3, length=5)
print(volume)

Output

30

Keyword arguments are also helpful for improving the readability of function calls, especially for functions with many arguments.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x