How to Parse Function Parameters with Defaults in Python

Create Python functions with default parameter values to make arguments optional and provide sensible fallbacks.

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

Python code

16 lines
Python 3.9+
def greet(name, greeting="Hello", punctuation="!"):
    """Greet a person with customizable greeting and punctuation."""
    return f"{greeting}, {name}{punctuation}"

def describe_fruit(fruit, color="unknown", ripe=False):
    """Describe a fruit with optional attributes."""
    status = "ripe" if ripe else "not ripe"
    return f"{fruit} is {color} and {status}"

if __name__ == "__main__":
    print(greet("Alice"))
    print(greet("Bob", "Hi"))
    print(greet("Charlie", "Hey", "!!!"))
    print(describe_fruit("apple"))
    print(describe_fruit("banana", "yellow", True))
    print(describe_fruit("cherry", ripe=True))

Output

stdout
Hello, Alice!
Hi, Bob!
Hey, Charlie!!!
apple is unknown and not ripe
banana is yellow and ripe
cherry is unknown and ripe

How it works

Default parameters let you define values that are used when arguments are omitted. In greet, greeting and punctuation default to "Hello" and "!" respectively, so calling greet("Alice") uses those defaults. When you supply a value, like greet("Bob", "Hi"), it overrides the default. Using keyword arguments like ripe=True makes your code more readable and lets you skip earlier parameters. The __name__ == "__main__" guard ensures the test calls only run when the script is executed directly, not when imported.

Common mistakes

  • Putting default parameters before non-default ones (syntax error)
  • Using mutable defaults like lists or dicts, which are shared across calls
  • Confusing keyword argument ordering with positional argument rules

Variations

  1. Use keyword-only arguments with `*` to force explicit naming
  2. Return a tuple instead of a string for more structured data

Real-world use cases

  • Building CLI tools where optional flags set default behavior without extra code.
  • API client functions that accept optional timeout or auth parameters with defaults.
  • Configuration loaders that fall back to sensible values when keys are missing.

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.