Generally if you have a function with parameters, while calling the function you pass the arguments in the same positional order. There is also an option of keyword arguments in Python where arguments are passed as key, value pair, since the parameters are identified by their names so keyword arguments are also known as named arguments.
For example here is a function where the positional arguments are passed.
def display_amount(message, amount): print(message, '%.2f ' % amount) display_amount("Total Amount is", 50.56)
Same function with keyword arguments can be written as-
def display_amount(message, amount): print(message, '%.2f ' % amount) display_amount(message="Total Amount is", amount=50.56)
As you can see now the code is more readable though more verbose. With keyword arguments you can even change the position of the arguments as the arguments are identified by name.
def display_amount(message, amount): print(message, '%.2f ' % amount) display_amount(amount=50.56, message="Total Amount is")
Output
Total Amount is 50.56
Mixing positional arguments with keyword arguments
You can have both positional arguments and keyword arguments in your function call but there is one restriction that positional arguments should come first followed by keyword arguments.
def display_amount(message, amount): print(message, '%.2f ' % amount) display_amount("Total Amount is", amount=50.56)
Output
Total Amount is 50.56
Not following that order results in error-
def display_amount(message, amount): print(message, '%.2f ' % amount) #display_amount("Total Amount is", amount=50.56) display_amount(message="Total Amount is", 50.56)
display_amount(message="Total Amount is", 50.56) ^ SyntaxError: positional argument follows keyword argument
That's all for this topic Keyword Arguments in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Python Tutorial Page
Related Topics
You may also like-