How to Use Default Parameter Values in Python Functions

Shows how to define and call Python functions with default parameter values, including overriding some or all defaults and using keyword arguments.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 14 views 0 copies

Python code

23 lines
Python 3.9+
def greet(name, greeting="Hello", punctuation="!"):
    """Return a greeting message using default parameters."""
    return f"{greeting}, {name}{punctuation}"

if __name__ == "__main__":
    # Using defaults
    print(greet("Alice"))
    
    # Overriding first default
    print(greet("Bob", "Hi"))
    
    # Overriding both defaults
    print(greet("Charlie", "Hey", "."))
    
    # Using keyword arguments
    print(greet("Diana", punctuation="?"))
    
    # Validating default behavior
    assert greet("Alice") == "Hello, Alice!"
    assert greet("Bob", "Hi") == "Hi, Bob!"
    assert greet("Charlie", "Hey", ".") == "Hey, Charlie."
    assert greet("Diana", punctuation="?") == "Hello, Diana?"
    print("All assertions passed.")

Output

stdout
Hello, Alice!
Hi, Bob!
Hey, Charlie.
Hello, Diana?
All assertions passed.

How it works

Default parameters let you call a function with fewer arguments than its full signature, filling in missing values automatically. The defaults are evaluated when the function is defined, not each time it's called. You can override individual defaults by passing values positionally or by name with keyword arguments. Keyword arguments make it clear which parameter you're setting and let you skip earlier defaults. This pattern keeps functions flexible while avoiding repetitive code.

Common mistakes

  • Using mutable defaults like lists or dicts, which persist between calls
  • Putting parameters with defaults before required parameters in the signature
  • Forgetting that keyword arguments must come after positional ones in a call

Variations

  1. Use *args and **kwargs to accept variable numbers of arguments with defaults
  2. Use functools.partial to fix default values at call time instead of definition time

Real-world use cases

  • Building reusable log formatters where the log level and timestamp format have sane defaults.
  • Constructing API client wrappers where retry counts and timeouts are optional via defaults.
  • Creating configurable UI builders that accept optional style or behavior flags.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.