Python: What is a keyword argument?

adamlombard

Adam Lombard

Posted on January 11, 2020

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! 鈽曪笍


馃挅 馃挭 馃檯 馃毄
adamlombard
Adam Lombard

Posted on January 11, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related