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! ️


原文链接:Python: What is a keyword argument?

© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容