Python

In Python, Default and Keyword Arguments provide flexibility in how functions are called. They allow you to design functions that can be used with varying levels of detail, making your code more robust and easier to read.

1. Default Arguments

A Default Argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.

  • Theory: This is useful when a function is usually called with the same values, but you want to allow for occasional changes.

  • Rule: Non-default arguments must come before default arguments in the function definition. For example, def func(a, b=5): is valid, but def func(a=5, b): will result in a SyntaxError.

Code Example: Default Arguments

Python
def greet(name, message="Welcome to the course"):
    """Greets a user with a default message."""
    print(f"Hello {name}, {message}")

# Calling with only the required argument
greet("Admin") 
# Output: Hello Admin, Welcome to the course

# Overriding the default value
greet("Student", "Happy Learning!") 
# Output: Hello Student, Happy Learning!

2. Keyword Arguments

Keyword Arguments allow you to pass arguments to a function by explicitly naming the parameter followed by the value (parameter_name=value).

  • Theory: When using keyword arguments, the order of the arguments does not matter. This is highly beneficial for functions with many parameters, as it makes the code "self-documenting."

  • Mixing: You can mix positional and keyword arguments, but positional arguments must always come first.

Code Example: Keyword Arguments

Python
def describe_pet(pet_name, animal_type="Dog"):
    """Displays information about a pet."""
    print(f"I have a {animal_type} named {pet_name}.")

# Using keyword arguments out of order
describe_pet(animal_type="Cat", pet_name="Whiskers")
# Output: I have a Cat named Whiskers.

# Positional and Keyword mixed
describe_pet("Buddy", animal_type="Golden Retriever")

3. Important Considerations

The "Mutable Default Argument" Trap

One of the most common pitfalls in Python is using a mutable object (like a list or dictionary) as a default value. Python evaluates default arguments only once at the time of function definition, not every time the function is called.

Incorrect Way:

Python
def add_item(item, my_list=[]): # The list is shared across all calls!
    my_list.append(item)
    return my_list

Correct Way (The Pythonic Way):

Python
def add_item(item, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(item)
    return my_list

Summary Table

Argument TypeSyntaxMain Benefit
Defaultdef func(a=10):Makes arguments optional.
Keywordfunc(a=20)Order doesn't matter; improves readability.
Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now