DEV Community

Adam Lombard
Adam Lombard

Posted on • Edited on

Python: What is a keyword argument?

Say we have a Python function which enables a user to introduce themself, with parameters for first, middle, and last names:

def my_name_is(first, middle, last):
   print(f"Hello, my name is {first} {middle} {last}.")
Enter fullscreen mode Exit fullscreen mode

Calling the function with appropriate positional arguments yields the expected introduction:

>>> my_name_is("Margaret", "Heafield", "Hamilton")
Hello, my name is Margaret Heafield Hamilton.
Enter fullscreen mode Exit fullscreen mode

Since we're passing positional arguments to our function, the position of the arguments matters:

>>> my_name_is("Heafield", "Hamilton", "Margaret")
Hello, my name is Heafield Hamilton Margaret.
Enter fullscreen mode Exit fullscreen mode

We could, instead, pass keyword arguments to the same function:

>>> my_name_is(first="Margaret", middle="Heafield", last="Hamilton"):
Hello, my name is Margaret Heafield Hamilton.
Enter fullscreen mode Exit fullscreen mode

Since we are now passing keyword arguments to our function, the position of the arguments does not matter:

>>> my_name_is(middle="Heafield", last="Hamilton", first="Margaret")
Hello, my name is Margaret Heafield Hamilton.
Enter fullscreen mode Exit fullscreen mode

More detailed information on keyword arguments can be found in the Python documentation.

Learn more about Margaret Hamliton.


Was this helpful? Did I save you some time?

🫖 Buy Me A Tea! ☕️


Top comments (2)

Collapse
 
xanderyzwich profile image
Corey McCarty

Keywords are cooler when you realize that you can pass a dictionary as kwags** and it will pull them out.

Collapse
 
adamlombard profile image
Adam Lombard

Thank you for the note! :)

I wrote another article about the use of *args and *kwargs: