Wednesday, 30 October 2019

Keyword Arguments in Python

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

  1. Python Functions : Returning Multiple Values
  2. Global Keyword in Python With Examples
  3. Local, Nonlocal And Global Variables in Python
  4. Python Conditional Statement - if, elif, else Statements
  5. Convert String to float in Python

You may also like-

  1. Namespace And Variable Scope in Python
  2. Inheritance in Python
  3. Python Program to Find Factorial of a Number
  4. Accessing Characters in Python String
  5. Serialization and Deserialization in Java
  6. java.lang.ClassCastException - Resolving ClassCastException in Java
  7. Linear Search (Sequential Search) Java Program
  8. Spring Boot spring-boot-starter-parent

No comments:

Post a Comment