[Type A] Working with Functions – Chapter 3 Sumita Arora

|
Table of Contents

5. What is the utility of:
(I) default arguments
(II) Keyword arguments?

Solution:

  • (I) Default arguments: Provide default values to parameters, allowing the function to be called without specifying those parameters.
Python
def greet(name="Guest", age=30):
    print("Hello,", name, "You are", age, "years old.")

# Calling the function without specifying arguments
greet()  # Output: Hello, Guest You are 30 years old.

# Calling the function with only one argument
greet("Alice")  # Output: Hello, Alice You are 30 years old.

In this example, the greet() function can be called without specifying any arguments, in which case default values of "Guest" and 30 are used for name and age respectively.

  • (II) Keyword arguments: Passed with the parameter name specified, allowing arguments to be passed in any order.
Python
def greet(name, age):
    print("Hello,", name, "You are", age, "years old.")

# Calling the function with arguments passed in any order using keyword arguments
greet(age=25, name="Bob")  # Output: Hello, Bob You are 25 years old.

In this example, the greet() function is called with arguments passed in any order using keyword arguments. The parameter names (name and age) are specified explicitly, allowing for flexibility in argument order.

"Spread the light within, illuminate the hearts around you. Sharing is not just an action, but a sacred journey of connecting souls."~ Anonymous

Leave a Reply

Your email address will not be published. Required fields are marked *