How to Use Default Parameters in Python Functions

Create a simple function with default parameters to build flexible, reusable greetings in Python.

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

Python code

10 lines
Python 3.6+
def greet(name, greeting="Hello", punctuation="!"):
    """Return a personalized greeting message."""
    return f"{greeting}, {name}{punctuation}"


if __name__ == "__main__":
    print(greet("Alice"))               
    print(greet("Bob", "Hi"))           
    print(greet("Charlie", greeting="Hey", punctuation="?"))  
    print(greet("Dana", punctuation="..."))

Output

stdout
Hello, Alice!
Hi, Bob!
Hey, Charlie?
Hello, Dana...

How it works

The greet function defines three parameters: name, greeting, and punctuation, with the last two having default values. When a caller omits an argument for these, Python automatically uses the default, making the function flexible without extra logic. Using keyword arguments like greeting="Hey" improves readability and allows you to skip earlier parameters. The if __name__ == "__main__": guard ensures the test calls run only when the script is executed directly, not when imported.

Common mistakes

  • Placing a parameter with a default before a parameter without one, which raises a SyntaxError.
  • Using mutable default values like lists or dicts, which are shared across calls and can cause bugs.
  • Forgetting that default values are evaluated once at function definition time, so dynamic defaults need a sentinel like None.

Variations

  1. Use `def greet(name, greeting='Hello', punctuation='!', /)` to make parameters positional-only.
  2. Call with all arguments positionally: `greet('Alice', 'Hi', '?')`.

Real-world use cases

  • Customizing log messages with optional severity levels or prefixes in a logging utility.
  • Building a configuration loader with optional environment-based overrides and defaults.
  • Creating API client methods where optional query parameters have sensible defaults.

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.