Write a python program to demonstrate the use of default arguments

1. Introduction

In this blog post, we will learn how to write a Python program that demonstrates the use of default arguments in functions. Default arguments are argument values that are specified in a function definition and are used if no value is passed for those arguments when the function is called. This feature adds flexibility and provides default behavior for functions in Python.

2. Program Steps

1. Define a function with one or more default arguments.

2. Call the function without passing the default argument(s) to see the default behavior.

3. Call the function again, this time passing different values, to override the default behavior.

3. Code Program


def greet(name, message="Hello"):
    # Print a greeting message
    print(f"{message}, {name}!")

# Step 2: Call the function without specifying the message
greet("Alice")

# Step 3: Call the function with a different message
greet("Bob", "Goodbye")

Output:

The first function call outputs: Hello, Alice!
The second function call outputs: Goodbye, Bob!

Explanation:

1. The function greet is defined with two parameters: name and message. The message parameter has a default value of "Hello". This means if no message is provided when the function is called, it will use "Hello".

2. When greet is called with just one argument ("Alice"), the default value of message is used. Therefore, it prints Hello, Alice!.

3. The second time greet is called with both arguments ("Bob" and "Goodbye"), the default value of message is overridden with "Goodbye". Hence, it prints Goodbye, Bob!.

This program demonstrates how default arguments in Python can be used to provide default values for parameters, making functions more flexible and user-friendly.


Comments