How to Create Functions with Default Parameters in Python

This code defines two Python functions using default parameters to handle missing arguments gracefully, demonstrating how to work with optional inputs and keyword arguments.

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

Python code

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


def create_profile(username="anonymous", age=0, city="Unknown", active=True):
    """Create a user profile dictionary with default values."""
    return {
        "username": username,
        "age": age,
        "city": city,
        "active": active,
    }


if __name__ == "__main__":
    # Using default parameters
    print(greet())                          # "Hello, Guest!"
    print(greet("Alice"))                   # "Hello, Alice!"
    print(greet("Bob", "Hi"))               # "Hi, Bob!"
    print(greet("Sam", "Hey", "?"))         # "Hey, Sam?"
    
    # Using keyword arguments to skip defaults
    print(greet(punctuation="!!!"))         # "Hello, Guest!!!"
    
    # Dictionary example
    print(create_profile())                 # Default profile
    print(create_profile("john_doe", 25, "NYC"))  # Partial defaults

Output

stdout
Hello, Guest!
Hello, Alice!
Hi, Bob!
Hey, Sam?
Hello, Guest!!!
{'username': 'anonymous', 'age': 0, 'city': 'Unknown', 'active': True}
{'username': 'john_doe', 'age': 25, 'city': 'NYC', 'active': True}

How it works

Default parameters let a function use a fallback value when an argument is omitted, making the function flexible and easier to call. The defaults are evaluated once at function definition time, so they work well with immutable types like strings and ints. Using keyword arguments like punctuation='!!!' lets you skip earlier parameters and override only the one you need. The create_profile function shows how defaults help build configuration-like dictionaries without requiring every field.

Common mistakes

  • Using mutable defaults like `def f(x=[])` can cause shared-state bugs.
  • Default parameters are evaluated at definition time, so don't rely on runtime values.
  • Forgetting that positional arguments must be passed in order if you don't use keywords.
  • Placing a parameter without a default before one with a default is a syntax error.

Variations

  1. Use `*args` and `**kwargs` to accept an arbitrary number of arguments.
  2. Use `functools.partial` to fix arguments ahead of time and create callable presets.

Real-world use cases

  • Building API client constructors that use sane defaults for host, timeout, and retries.
  • Creating configuration objects where most fields have default values but can be overridden by user settings.
  • Writing CLI helper functions that provide sensible defaults for flags like verbose or color.

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.