How to Define a Function with Default Parameter Values in Python

This code demonstrates defining a Python function with default parameter values, showing how to call it with zero, one, or two arguments.

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

Python code

15 lines
Python 3.9+
def greet(name: str = "World", punctuation: str = "!") -> str:
    """Return a greeting message using default parameter values."""
    message = f"Hello, {name}{punctuation}"
    return message


if __name__ == "__main__":
    # Call with no arguments – uses both defaults
    print(greet())

    # Call with one argument – uses default punctuation
    print(greet("Python"))

    # Call with both arguments – overrides both defaults
    print(greet("Developer", "."))

Output

stdout
Hello, World!
Hello, Python!
Hello, Developer.

How it works

The greet function declares two parameters, name and punctuation, each with a default value. When you call the function without providing an argument for a parameter, Python automatically uses the default. This allows the function to be flexible—handling calls with anywhere from zero to two arguments. The default values are evaluated once at function definition time, which is fine for immutable types like strings. The function's type hints (name: str, -> str) improve readability and enable static checking.

Common mistakes

  • Setting default parameters to mutable objects like lists or dictionaries, which can cause shared-state bugs.
  • Forgetting that default arguments are evaluated only once, making them unsuitable for dynamic values like timestamps.
  • Omitting type hints, making the function less self-documenting and harder to maintain.

Variations

  1. Use keyword arguments when calling to make the intent clear: `greet(name="Python", punctuation="?")`.
  2. Leverage `functools.partial` to create a new function with fixed defaults.

Real-world use cases

  • Providing sensible defaults in a logging helper so callers can override log level only when needed.
  • Building API client methods where optional query parameters default to a standard set.
  • Creating test fixtures where most test cases use default setup, with occasional overrides.

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.