Class 12 : Python Functions | Keyword Arguments

Python Keyword Arguments

Normally When we call a function with some values, these values get assigned to the arguments according to their position.

Example:1

def greet(name,msg):
       print(“Hello”,name,” “,msg)

For example, in the above function greet(),
when we called it as

greet(“sumit”,”How do you do?”),

the value

“sumit” gets assigned to the argument name and
“How do you do?” to msg.

def greet(name,msg):
     print("Hello",name,"  ",msg)

greet("sumit","How do you do?")

Output:

Hello sumit How do you do?
>>>

Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed.
Following calls to the above function are all valid and produce the same result.

def greet(name=”amit”,msg=”how are you”):
          print(“Hello “,name,” “,msg)

#function calling
greet(name = “sumit”,msg = “How do you do?”)

greet(msg = “How do you do?”,name = “sumit”)

greet(name=”sumit”,msg = “Hope all is fine”)

greet(“sumit”,msg = “How do you do?”)

As we can see, we can mix positional arguments with keyword arguments during a function call. But we must keep in mind that keyword arguments must follow positional arguments.
Having a positional argument after keyword arguments will result into errors. For example the function call as follows:

greet(name=”sumit”,”How do you do?”) #error
Will result into error as:
SyntaxError: non-keyword arg after keyword arg

#function definition
def greet(name="amit",msg="how are you"):
     print("Hello ",name," ",msg)

#function calling
greet(name = "sumit",msg = "How do you do?")

Output:

Hello sumit How do you do?
>>>

#function definition
def greet(name="amit",msg="how are you"):
     print("Hello ",name," ",msg)

#function calling
greet(msg = "How do you do?",name = "sumit")

Output:

Hello sumit How do you do?
>>>

#function definition
def greet(name="amit",msg="how are you"):
     print("Hello ",name," ",msg)

#function calling
greet(name="Mohit",msg = "Hope all is fine")

Output:

Hello Mohit Hope all is fine
>>>

#function definition
def greet(name="amit",msg="how are you"):
     print("Hello ",name," ",msg)

#function calling
greet("Mayank",msg = "How do you do?")

Output:

Hello Mayank How do you do?
>>>