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}.")
Calling the function with appropriate positional arguments yields the expected introduction:
>>> my_name_is("Margaret", "Heafield", "Hamilton")
Hello, my name is Margaret Heafield Hamilton.
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.
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.
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.
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?
Top comments (2)
Keywords are cooler when you realize that you can pass a dictionary as kwags** and it will pull them out.
Thank you for the note! :)
I wrote another article about the use of
*args
and*kwargs
:Python: What are *args and **kwargs?
Adam Lombard (he/him) ・ Jan 12 '20 ・ 2 min read