How to use function defaults in Python

Define Python functions with default parameter values so callers can omit arguments and use sensible fallbacks.

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

Python code

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

def describe_pet(pet_name, animal_type="dog"):
    """Display information about a pet with a default animal type."""
    print(f"I have a {animal_type} named {pet_name}.")

def multiply(x, y=2, z=3):
    """Multiply numbers, using defaults for missing arguments."""
    return x * y * z

if __name__ == "__main__":
    # Using defaults for all parameters
    print(greet())

    # Overriding some defaults
    print(greet("Alice"))
    print(greet("Bob", "Hi"))
    print(greet("Charlie", "Hey", "."))

    # Demonstrating a function with a default parameter
    describe_pet("Rex")
    describe_pet("Whiskers", "cat")

    # Function with multiple defaults
    print(multiply(5))          # 5 * 2 * 3 = 30
    print(multiply(5, 4))       # 5 * 4 * 3 = 60
    print(multiply(5, 4, 2))    # 5 * 4 * 2 = 40

Output

stdout
Hello, Guest!
Hello, Alice!
Hi, Bob!
Hey, Charlie.
I have a dog named Rex.
I have a cat named Whiskers.
30
60
40

How it works

Default parameters in Python let you set fallback values for arguments that are not passed. When a caller omits an argument, Python automatically uses the default value defined in the function signature. This example shows how defaults work for strings, printing, and multiple numeric arguments. Defaults are evaluated once when the function is defined, so use immutable types like strings or numbers for safety.

Common mistakes

  • Putting parameters with defaults before parameters without defaults (SyntaxError)
  • Using mutable defaults like lists or dicts that persist across calls
  • Forgetting that defaults are evaluated once at definition time

Variations

  1. Use keyword-only arguments with `*` before default parameters to force explicit naming.
  2. Use `None` as the default and assign a fresh mutable object inside the function.

Real-world use cases

  • Building a configurable HTTP client where timeout and retries have sensible defaults.
  • Writing logging helpers that default to DEBUG but accept a custom level.
  • Creating CLI tools where optional flags default to safe values.

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.