Default Parameter Values and Optionality

🏷️ Functions / Parameters and Arguments

🧠 Context Introduction

When writing functions in Python, you will often find that certain parameters don't always need a new value every time the function is called. Sometimes, a sensible fallback value works perfectly. This is where default parameter values come into play. They allow you to define a function with parameters that are optional—if the caller doesn't provide a value, the default is used automatically. This makes your functions more flexible, reduces repetitive code, and keeps your function calls clean and readable.


⚙️ What Are Default Parameter Values?

A default parameter value is a value assigned to a parameter in the function definition. If the caller omits that argument, Python uses the default. If the caller provides a value, the provided value overrides the default.

  • Default values are specified using an equals sign (=) right after the parameter name in the function definition.
  • Parameters with defaults are optional; parameters without defaults are required.
  • All required parameters must come before any optional parameters in the function signature.

Example concept: - A function that greets a user. If no name is given, it defaults to "Guest". - A function that calculates a discount. If no discount percentage is given, it defaults to 10%.


🛠️ How to Define Default Parameters

When defining a function, you assign a default value to a parameter like this:

  • Function definition: def function_name(param1, param2=default_value):
  • The parameter param2 is optional. If not provided, it takes default_value.
  • The parameter param1 is required—it must always be provided.

Simple example in practice: - Define a function called connect_to_server with a required parameter host and an optional parameter port that defaults to 22 (standard SSH port). - If you call connect_to_server("192.168.1.10"), it uses port 22. - If you call connect_to_server("192.168.1.10", 2222), it uses port 2222.


📊 Comparison: Required vs. Optional Parameters

Aspect Required Parameters Optional Parameters (with defaults)
Must be provided? Yes No
Position in function signature Come first Come after all required parameters
Default value None Defined in the function definition
Flexibility Less flexible—always needs a value More flexible—caller can skip it
Use case For values that are always needed For values that have a sensible fallback

🕵️ Common Patterns and Best Practices

  • Use defaults for configuration values: For example, a function that reads a log file might default to reading the last 10 lines, but allow the caller to specify a different number.
  • Avoid mutable default values like lists or dictionaries: If you use a list as a default, it gets created once when the function is defined, not each time the function is called. This can lead to unexpected behavior. Instead, use None as the default and create the mutable object inside the function.
  • Keep defaults simple: Use strings, numbers, booleans, or None as default values. These are immutable and safe.
  • Document your defaults: When writing a function, make it clear in the docstring what the default value is and what it does.

Example of a safe pattern with mutable defaults: - Instead of def add_item(item, cart=[]):, use def add_item(item, cart=None): and then inside the function, set if cart is None: cart = [].


✅ Why This Matters for Engineers

  • Cleaner code: You don't need to write multiple versions of the same function just to handle different numbers of arguments.
  • Backward compatibility: When updating a function, adding a new parameter with a default value won't break existing code that calls the function without that parameter.
  • Readable function calls: Callers only need to specify the values that differ from the defaults, making the intent of the code clearer.
  • Less error-prone: Defaults reduce the chance of forgetting to pass a common value, like a timeout or a retry count.

💡 Quick Summary

  • Default parameter values make function parameters optional.
  • They are defined with an equals sign in the function signature.
  • Required parameters must come before optional ones.
  • Use immutable defaults (like None, numbers, or strings) to avoid bugs.
  • Defaults make your functions more flexible, easier to use, and safer to maintain.

By mastering default parameter values, you will write functions that are both powerful and forgiving—perfect for building robust and maintainable Python code.


Default parameter values let you define fallback values for function parameters, making those parameters optional when calling the function.

🎯 Example 1: Simple default parameter value

This example shows a function with one required parameter and one parameter with a default value.

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

result = greet("Alice")
print(result)

📤 Output: Hello, Alice!


🎯 Example 2: Overriding a default parameter value

This example shows how to pass a different value to override the default.

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

result = greet("Bob", "Good morning")
print(result)

📤 Output: Good morning, Bob!


🎯 Example 3: Multiple parameters with default values

This example shows a function with several optional parameters, each having a default value.

def create_profile(name, age=30, city="Unknown", active=True):
    profile = f"Name: {name}, Age: {age}, City: {city}, Active: {active}"
    return profile

result = create_profile("Carol")
print(result)

📤 Output: Name: Carol, Age: 30, City: Unknown, Active: True


🎯 Example 4: Mixing required and optional parameters

This example shows required parameters must come before any parameters with default values.

def calculate_cost(price, quantity, tax_rate=0.08, discount=0.0):
    subtotal = price * quantity
    tax = subtotal * tax_rate
    total = subtotal + tax - discount
    return total

result = calculate_cost(25.00, 3)
print(result)

📤 Output: 81.0


🎯 Example 5: Practical use — logging with optional timestamp

This example shows a real-world pattern where default values make functions flexible for engineers.

import datetime

def log_message(message, level="INFO", timestamp=None):
    if timestamp is None:
        timestamp = datetime.datetime.now()
    log_entry = f"[{level}] {timestamp}: {message}"
    return log_entry

result1 = log_message("System started")
result2 = log_message("Error occurred", level="ERROR")
print(result1)
print(result2)

📤 Output: [INFO] 2025-04-04 10:30:00.123456: System started
📤 Output: [ERROR] 2025-04-04 10:30:00.123456: Error occurred


Comparison Table: Required vs. Optional Parameters

Feature Required Parameters Optional Parameters (with defaults)
Must be provided when calling? Yes No
Position in function definition Before optional parameters After required parameters
Default value assigned Never Always
Can be omitted in function call? No Yes
Example def add(a, b) def add(a, b=0)

🧠 Context Introduction

When writing functions in Python, you will often find that certain parameters don't always need a new value every time the function is called. Sometimes, a sensible fallback value works perfectly. This is where default parameter values come into play. They allow you to define a function with parameters that are optional—if the caller doesn't provide a value, the default is used automatically. This makes your functions more flexible, reduces repetitive code, and keeps your function calls clean and readable.


⚙️ What Are Default Parameter Values?

A default parameter value is a value assigned to a parameter in the function definition. If the caller omits that argument, Python uses the default. If the caller provides a value, the provided value overrides the default.

  • Default values are specified using an equals sign (=) right after the parameter name in the function definition.
  • Parameters with defaults are optional; parameters without defaults are required.
  • All required parameters must come before any optional parameters in the function signature.

Example concept: - A function that greets a user. If no name is given, it defaults to "Guest". - A function that calculates a discount. If no discount percentage is given, it defaults to 10%.


🛠️ How to Define Default Parameters

When defining a function, you assign a default value to a parameter like this:

  • Function definition: def function_name(param1, param2=default_value):
  • The parameter param2 is optional. If not provided, it takes default_value.
  • The parameter param1 is required—it must always be provided.

Simple example in practice: - Define a function called connect_to_server with a required parameter host and an optional parameter port that defaults to 22 (standard SSH port). - If you call connect_to_server("192.168.1.10"), it uses port 22. - If you call connect_to_server("192.168.1.10", 2222), it uses port 2222.


📊 Comparison: Required vs. Optional Parameters

Aspect Required Parameters Optional Parameters (with defaults)
Must be provided? Yes No
Position in function signature Come first Come after all required parameters
Default value None Defined in the function definition
Flexibility Less flexible—always needs a value More flexible—caller can skip it
Use case For values that are always needed For values that have a sensible fallback

🕵️ Common Patterns and Best Practices

  • Use defaults for configuration values: For example, a function that reads a log file might default to reading the last 10 lines, but allow the caller to specify a different number.
  • Avoid mutable default values like lists or dictionaries: If you use a list as a default, it gets created once when the function is defined, not each time the function is called. This can lead to unexpected behavior. Instead, use None as the default and create the mutable object inside the function.
  • Keep defaults simple: Use strings, numbers, booleans, or None as default values. These are immutable and safe.
  • Document your defaults: When writing a function, make it clear in the docstring what the default value is and what it does.

Example of a safe pattern with mutable defaults: - Instead of def add_item(item, cart=[]):, use def add_item(item, cart=None): and then inside the function, set if cart is None: cart = [].


✅ Why This Matters for Engineers

  • Cleaner code: You don't need to write multiple versions of the same function just to handle different numbers of arguments.
  • Backward compatibility: When updating a function, adding a new parameter with a default value won't break existing code that calls the function without that parameter.
  • Readable function calls: Callers only need to specify the values that differ from the defaults, making the intent of the code clearer.
  • Less error-prone: Defaults reduce the chance of forgetting to pass a common value, like a timeout or a retry count.

💡 Quick Summary

  • Default parameter values make function parameters optional.
  • They are defined with an equals sign in the function signature.
  • Required parameters must come before optional ones.
  • Use immutable defaults (like None, numbers, or strings) to avoid bugs.
  • Defaults make your functions more flexible, easier to use, and safer to maintain.

By mastering default parameter values, you will write functions that are both powerful and forgiving—perfect for building robust and maintainable Python code.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

Default parameter values let you define fallback values for function parameters, making those parameters optional when calling the function.

🎯 Example 1: Simple default parameter value

This example shows a function with one required parameter and one parameter with a default value.

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

result = greet("Alice")
print(result)

📤 Output: Hello, Alice!


🎯 Example 2: Overriding a default parameter value

This example shows how to pass a different value to override the default.

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

result = greet("Bob", "Good morning")
print(result)

📤 Output: Good morning, Bob!


🎯 Example 3: Multiple parameters with default values

This example shows a function with several optional parameters, each having a default value.

def create_profile(name, age=30, city="Unknown", active=True):
    profile = f"Name: {name}, Age: {age}, City: {city}, Active: {active}"
    return profile

result = create_profile("Carol")
print(result)

📤 Output: Name: Carol, Age: 30, City: Unknown, Active: True


🎯 Example 4: Mixing required and optional parameters

This example shows required parameters must come before any parameters with default values.

def calculate_cost(price, quantity, tax_rate=0.08, discount=0.0):
    subtotal = price * quantity
    tax = subtotal * tax_rate
    total = subtotal + tax - discount
    return total

result = calculate_cost(25.00, 3)
print(result)

📤 Output: 81.0


🎯 Example 5: Practical use — logging with optional timestamp

This example shows a real-world pattern where default values make functions flexible for engineers.

import datetime

def log_message(message, level="INFO", timestamp=None):
    if timestamp is None:
        timestamp = datetime.datetime.now()
    log_entry = f"[{level}] {timestamp}: {message}"
    return log_entry

result1 = log_message("System started")
result2 = log_message("Error occurred", level="ERROR")
print(result1)
print(result2)

📤 Output: [INFO] 2025-04-04 10:30:00.123456: System started
📤 Output: [ERROR] 2025-04-04 10:30:00.123456: Error occurred


Comparison Table: Required vs. Optional Parameters

Feature Required Parameters Optional Parameters (with defaults)
Must be provided when calling? Yes No
Position in function definition Before optional parameters After required parameters
Default value assigned Never Always
Can be omitted in function call? No Yes
Example def add(a, b) def add(a, b=0)