Introduction

One powerful feature of python is the ability to use keyword parameters in functions. This Python tutorial aims to guide you through the concept of keyword parameters in Python. It covers the basics of understanding what keyword parameters are, their use in function design and implementation, and scenarios where they are best suited for optimal results. This tutorial is appropriate for individuals with basic knowledge of Python programming and wants to learn about keyword parameters to enhance their coding skills.

Keyword parameters : 

  • Python allows use of keyword parameters in functions.
  • A parameter with two asterisk is called a keyword parameter in Python.
  • for example :

def my_func(a, b, **kwargs):
 	# function code

# Here - **kwargs is called keyword parameter.

  • It is a convention to name the keyword parameter as  **kwargs  but it is not mandatory to name it as kwargs. 
  • We can name it as anything e.g.  **employees, **ids, **price  etc.
  • A function with keyword parameter can accept variable number of arguments i.e. zero or more parameters.
  • The arguments in case of keyword parameter are passed as dictionary.
  • We can pass a dictionary as an argument by using two asterisk.
  • The  **kwargs  should always be the last parameter of the function.
  • Code Sample :

def my_func(a, b, **kwargs):
    print("Value of a = ", a)
    print("Value of b = ", b)
    print("Value of kwargs = ", kwargs)
    print()

    print("Iterating over kwargs")
    # using for loop
    for key in kwargs.keys():
        print(key,kwargs[key])

# Calling my_func
d = {"first":30, "second":40, "third":50}
my_func(10, 20, **d)

# Output
# Value of a =  10
# Value of b =  20
# Value of kwargs =  {'first': 30, 'second': 40, 'third': 50}

# Iterating over kwargs
# first 30
# second 40
# third 50

Prev. Tutorial : Variadic Functions

Next Tutorial : Keyword Arguments