How to Use Default Parameter Values in Python Functions

This code demonstrates how to define a Python function with default parameters and call it with varying numbers of arguments to see the defaults applied.

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

Python code

8 lines
Python 3.9+
def greet(name, greeting="Hello", punctuation="!"):
    message = f"{greeting}, {name}{punctuation}"
    print(message)

if __name__ == "__main__":
    greet("Alice")
    greet("Bob", "Hi")
    greet("Charlie", "Hey", "?")

Output

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

How it works

Default parameter values are specified in the function definition using an equals sign. When a caller omits an argument for that parameter, Python uses the default value. This makes functions flexible and reduces code duplication. The function prints a formatted greeting using an f-string. The if __name__ == "__main__": guard ensures the demo code only runs when the script is executed directly, not when imported.

Common mistakes

  • Using mutable defaults like `[]` or `{}` which are shared across calls
  • Placing parameters without defaults after parameters with defaults, causing a SyntaxError
  • Forgetting that default values are evaluated once at function definition time

Variations

  1. Return the string instead of printing it: `return f"{greeting}, {name}{punctuation}"`
  2. Use keyword arguments in calls: `greet(name="Alice", punctuation="!")`

Real-world use cases

  • Logging functions that accept optional severity levels and formatting with default values.
  • API client wrappers that set default timeouts or retry counts when not specified by the caller.
  • Configuration loaders that default to common file paths or encoding when no override is provided.

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.