When defining functions in Python, you can use keyword arguments and optional parameters to make function calls more flexible.


1️⃣ Keyword Arguments (Named Arguments)

Keyword arguments allow you to specify function parameters by name when calling a function. This improves readability and eliminates the need to remember the order of parameters.

Example:

def greet(name, message):
    print(f"{message}, {name}!")

# Using keyword arguments
greet(name="Alice", message="Good Morning")
greet(message="Hello", name="Bob")  # Order does not matter

Output:

Good Morning, Alice!
Hello, Bob!

👉 Why use keyword arguments?
✔️ Makes the function call more readable.
✔️ You don’t have to remember the parameter order.


2️⃣ Default (Optional) Parameters

A function can have default values for some parameters. If the caller does not provide a value, the function uses the default.

Example:

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

# Calling the function with and without the optional parameter
greet("Alice")  # Uses default message
greet("Bob", "Good Morning")  # Overrides default message

Output:

Hello, Alice!
Good Morning, Bob!

👉 Why use default parameters?
✔️ Makes parameters optional.
✔️ Avoids errors when arguments are missing.


3️⃣ Combining Positional, Keyword, and Default Arguments

You can mix positional and keyword arguments in a function.

Example:

def describe_pet(name, species="dog"):
    print(f"{name} is a {species}.")

describe_pet("Buddy")  # Uses default species
describe_pet("Whiskers", "cat")  # Overrides default species
describe_pet(species="rabbit", name="Thumper")  # Keyword arguments

Output:

Buddy is a dog.
Whiskers is a cat.
Thumper is a rabbit.

4️⃣ Using *args (Variable-Length Positional Arguments)

If you don’t know the number of arguments beforehand, use *args to accept multiple values.

Example:

def add_numbers(*args):
    return sum(args)

print(add_numbers(1, 2, 3))       # Output: 6
print(add_numbers(4, 5, 6, 7, 8))  # Output: 30

👉 Why use *args?
✔️ Allows passing multiple values.
✔️ Handles dynamic arguments.


5️⃣ Using **kwargs (Variable-Length Keyword Arguments)

**kwargs allows passing multiple keyword arguments as a dictionary.

Example:

def person_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

person_info(name="Alice", age=25, city="New York")

Output:

name: Alice
age: 25
city: New York

👉 Why use **kwargs?
✔️ Allows flexible keyword arguments.
✔️ Useful for passing configurations.


6️⃣ Function with *args and **kwargs Together

You can combine *args and **kwargs in a function.

Example:

def display_info(*args, **kwargs):
    print("Positional arguments:", args)
    print("Keyword arguments:", kwargs)

display_info(1, 2, 3, name="Alice", age=25)

Output:

Positional arguments: (1, 2, 3)
Keyword arguments: {'name': 'Alice', 'age': 25}

🔹 Summary Table

Concept Description Example
Keyword Arguments Specify parameters by name greet(name="Alice", message="Hi")
Default Parameters Provide default values for parameters def greet(name, msg="Hello"):
*args Allows multiple positional arguments def add(*args):
**kwargs Allows multiple keyword arguments def info(**kwargs):
Mixing *args and **kwargs Handles both positional and keyword arguments def display(*args, **kwargs):

Would you like real-world examples using these concepts? 🚀


Leave a Reply

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