Python tutorial to call a function using keyword argument

Python tutorial to call a function using keyword arguments :

In this python tutorial, we will learn what is keyword arguments and how to use Keyword arguments in a function. Normally, a function in python looks like :

def myFunction(first, second):
	…… 
	…..

Here, to call this function we need to pass values for both of the parameters first and second. If we don’t send any value to any of these parameter , it will not run. These are known as default arguments.

Keyword arguments are optional arguments. By default, they have one value assigned in the definition of the function. If you don’t set any value while calling the function , it will take the default value. But , if you set any value , it will take the new value. I will explain it with an example below .

Keyword Arguments :

To understand about Keyword Argument, let’s take a look at the below program :

def welcomeUser(name , message = "Welcome To Our Blog.",secondMessage = "Subscribe to get learn more tutorials like this."):
	print("Hello",name+" !!")
	print(message)
	print(secondMessage)

1. This program takes three arguments. First one name is a default argument. We will always have to add it.
2. Argument message is a keyword argument. If we don’t pass any value to this argument, it will print out the value mentioned in the definition.
3. Argument secondMessage is also a keyword argument as like above.

Pass value for default keyword :

def welcomeUser(name , message = "Welcome To Our Blog.",secondMessage = "Subscribe to get learn more tutorials like this."):
	print("Hello",name+" !!")
	print(message)
	print(secondMessage)

welcomeUser(name = "Albert")

It will produce the below output :

Hello Alex !!
Welcome To Our Blog.
Subscribe to get learn more tutorials like this.

So, it will take the value of name and takes the default values for the other keyword arguments.

welcomeUser("Albert”)

The above line will also print the same output.

Passing value to a keyword argument :

def welcomeUser(name , message = "Welcome To Our Blog.",secondMessage = "Subscribe to get learn more tutorials like this."):
	print("Hello",name+" !!")
	print(message)
	print(secondMessage)

welcomeUser(name = "Albert", message = "Welcome Again!!")
Output :
Hello Albert !!
Welcome Again!!
Subscribe to get learn more tutorials like this.

The below call will print the same output :

welcomeUser(message = "Welcome Again!!",name = "Albert")

But, if we don’t mention the name, it will throw an error.

welcomeUser(message = "Welcome Again!!", "Albert”)

It will throw one error.

welcomeUser(message = "Welcome Again!!"")

It will also throw same error because the value for default keyword name should be mentioned.

Leave a Reply