Write a python program to demonstrate the use of keyword arguments

1. Introduction

This blog post aims to demonstrate the use of keyword arguments in Python. Keyword arguments are a way to pass values to a function with a key-value pair, making the code more readable and allowing the function parameters to be passed in any order.

2. Program Steps

1. Define a function with several parameters.

2. Call the function using keyword arguments.

3. Call the function again using keyword arguments in a different order.

3. Code Program


def display_info(name, age, city):
    # Printing the information
    print(f"Name: {name}, Age: {age}, City: {city}")

# Step 2: Call the function using keyword arguments
display_info(name="Alice", age=30, city="New York")

# Step 3: Call the function using keyword arguments in a different order
display_info(age=25, city="Los Angeles", name="Bob")

Output:

The first function call outputs: Name: Alice, Age: 30, City: New York
The second function call outputs: Name: Bob, Age: 25, City: Los Angeles

Explanation:

1. The function display_info is defined with three parameters: name, age, and city.

2. When calling display_info the first time, the arguments are passed using their respective keywords. This clarifies which value corresponds to which parameter.

3. In the second call to display_info, the order of the keyword arguments is changed (age, city, name). One of the advantages of keyword arguments is that the order of the arguments can be different from the order in which the parameters are defined in the function.

This program showcases how keyword arguments in Python enhance the readability of function calls and provide flexibility in the order of arguments.


Comments