Python Introduction | Functions | Keyword Arguments

Arguments are a surprisingly versatile part of a function. Besides passing values in the usual way, they provide several options.

One option is a keyword argument. This feature lets you use a keyword, or name, when passing an argument.

Function Definition 3

def function(key1=initial_value1, key2=initial_value2, ...):

Specify a key and an initial value. You can then pass arguments by using their keys. Ordinary arguments have a fixed order, but keyword arguments let you provide values regardless of their order.

Because an initial value is available, you can also omit the argument. The function uses the default value when an argument is omitted. An ordinary argument must receive a value, but a keyword argument can work like an optional argument.

Consider the following example.

def showMsg(name, header='Hello', footer='How are you?'): 
    print(header + "," + name + ". " + footer) 
   
showMsg("Taro") 
showMsg("철수", '안녕', '건강하니?') 
showMsg("영희", footer='잘지내니?', header='야') 

The code calls showMsg in three ways. A call such as showMsg("Taro") works with only the first argument because the second and third arguments use their initial values.

Keyword names are optional. If you omit the names, specify arguments in the order in which they were defined. If you include keyword names, you can provide the arguments in any order.

This example mixes arguments without default values and arguments with default values. In this situation, define arguments without default values first and keyword arguments afterward. Defining an argument without a default value after a keyword argument causes a syntax error.