How to Use Default Parameters in Python Functions

A beginner-friendly Python function that uses default parameters to compare two numbers with equal, greater, or less operations.

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

Python code

15 lines
Python 3.9+
def compare(a, b, operation="equal"):
    if operation == "equal":
        return a == b
    elif operation == "greater":
        return a > b
    elif operation == "less":
        return a < b
    else:
        return f"Unknown operation: {operation}"

if __name__ == "__main__":
    print(compare(5, 5))
    print(compare(5, 3, "greater"))
    print(compare(5, 3, "less"))
    print(compare(5, 3, "different"))

Output

stdout
True
True
False
Unknown operation: different

How it works

The operation parameter defaults to "equal", so calling compare(5, 5) skips the operation argument and compares for equality. The if/elif chain returns a boolean for each supported operation, or a descriptive string when the operation is unrecognized. Default parameters let you create flexible functions that still work with minimal arguments. The __main__ guard ensures the demo runs only when the script is executed directly, not when imported.

Common mistakes

  • Forgetting to pass a default value when the parameter has a default — this leads to a TypeError about missing arguments.
  • Default parameters are evaluated once at definition time, not each call — avoid mutable defaults like `[]` or `{}` here.

Variations

  1. Use a match statement instead of if/elif for more readable operation handling in Python 3.10+.
  2. Return a custom error with `raise ValueError` for unknown operations instead of a string.

Real-world use cases

  • Building a CLI tool where a sorting flag defaults to ascending order unless specified.
  • Implementing a config parser that assumes a default JSON format but allows overrides.
  • Writing a validation function that checks equality by default but can switch to greater-than for range checks.

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.