Default Arguments

Default Arguments in Python Functions

Default arguments allow you to specify default values for function parameters. If a value isn’t provided for that parameter when the function is called, Python uses the default value instead.

Basic Syntax

python

def function_name(parameter=default_value):
    # function body

Simple Examples

Example 1: Basic Default Argument

python

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

# Using the function
greet("Alice")      # Output: Hello, Alice!
greet()             # Output: Hello, Guest!

Example 2: Multiple Default Arguments

python

def order_food(item="pizza", quantity=1):
    print(f"Order: {quantity} {item}(s)")

order_food("burger", 2)    # Output: Order: 2 burger(s)
order_food("pasta")        # Output: Order: 1 pasta(s)
order_food()               # Output: Order: 1 pizza(s)

Example 3: Mixing Regular and Default Arguments

python

def calculate_area(length, width=10):
    area = length * width
    print(f"Area: {area} square units")

calculate_area(5, 3)    # Output: Area: 15 square units
calculate_area(5)       # Output: Area: 50 square units

Example 4: Practical Use Case

python

def create_user_profile(name, age, country="Unknown"):
    print(f"Name: {name}")
    print(f"Age: {age}")
    print(f"Country: {country}")
    print("-" * 20)

create_user_profile("John", 25, "USA")
create_user_profile("Sarah", 30)  # Country will be "Unknown"

Important Rules

  1. Default arguments must come after non-default arguments:

python

# Correct:
def func(a, b=10):
    pass

# Wrong:
# def func(a=10, b):  # This will cause an error
#     pass
  1. Default values are evaluated only once when the function is defined:

python

def add_item(item, shopping_list=[]):
    shopping_list.append(item)
    return shopping_list

print(add_item("apple"))    # Output: ['apple']
print(add_item("banana"))   # Output: ['apple', 'banana']

Best Practice for Mutable Default Arguments

For lists, dictionaries, or other mutable objects, it’s better to use None as the default:

python

def add_item_better(item, shopping_list=None):
    if shopping_list is None:
        shopping_list = []
    shopping_list.append(item)
    return shopping_list

print(add_item_better("apple"))    # Output: ['apple']
print(add_item_better("banana"))   # Output: ['banana']

Key Benefits

  • Flexibility: Functions can be called with fewer arguments
  • Readability: Makes function calls cleaner when many parameters have common values
  • Backward compatibility: You can add new parameters without breaking existing code

Default arguments make your functions more versatile and user-friendly!

Similar Posts

Leave a Reply

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