Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Why Functions?Parameters & ArgumentsReturn StatementsScopeDefault ParametersVariable Arguments (*args)Lambda FunctionsDecoratorsFunctional ProgrammingBest Practices
Python/Functions/Default Parameters

⚡ Default Parameters — Optional Arguments with Sensible Defaults

A default parameter is a value the function uses if you don't provide one. This makes your function more flexible because callers can skip that argument if they want to use the default. You specify the default by adding an equals sign and value after the parameter name in the function definition.


🎯 What Are Default Parameters?

A default parameter lets you specify what value a function should use if the caller doesn't provide an argument for that parameter. This is useful for optional features or settings where you have a sensible, commonly-used value. When a caller omits an argument that has a default, the function automatically uses the default value instead.

def greet(name="Friend"):
    print(f"Hello, {name}!")

greet()          # Uses default: "Hello, Friend!"
greet("Alice")   # Uses provided: "Hello, Alice!"

If you don't pass `name`, the function uses `"Friend"`.


💡 Real Example

Default parameters are perfect for optional settings that most of the time use the same value. You're giving users the option to customize, but they don't have to if they're happy with what you chose. This keeps function calls simple and readable, especially when most people will use the defaults.

def create_post(title, color="blue"):
    print(f"Post: {title} (color: {color})")

create_post("Hello")              # Uses default blue
create_post("Hello", "red")       # Uses red instead

📝 Multiple Defaults

You can have multiple parameters with defaults:

def make_pizza(size="medium", crust="thin", cheese=True):
    print(f"Making a {size} pizza with {crust} crust")
    if cheese:
        print("Adding cheese!")

make_pizza()                           # Uses all defaults
make_pizza("large")                    # size=large, others default
make_pizza("large", "thick")           # size and crust specified
make_pizza("large", "thick", False)    # All specified

✅ Default Parameter Rules

1. Required parameters come first — Parameters without defaults must come before parameters with defaults

2. Defaults can be any value — Numbers, strings, lists, even None

3. Called left to right — Arguments are assigned by position

# ✅ Correct - required first, then defaults
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

# ❌ Wrong - default can't come before required
def greet(greeting="Hello", name):  # SyntaxError!
    pass

🎨 Real-World Examples

Create File with Default Settings

def create_file(filename, format="txt", backup=True):
    print(f"Creating {filename}.{format}")
    if backup:
        print(f"Backup enabled")

create_file("report")                     # .txt with backup
create_file("document", "pdf")            # PDF with backup
create_file("photo", "jpg", False)        # JPG, no backup

Calculate Price with Default Tax

def calculate_total(amount, tax_rate=0.1):
    total = amount + (amount * tax_rate)
    return total

price1 = calculate_total(100)           # Uses 10% tax
price2 = calculate_total(100, 0.15)     # Uses 15% tax

🔑 Key Takeaways

ConceptRemember
Default parameterProvides a fallback value
Optional argumentsCallers can skip arguments with defaults
Order mattersRequired parameters before default parameters
FlexibilityMakes functions easier to use
Sensible defaultsChoose values that most users want

🔗 What's Next?

Now let's learn about *args — how to accept any number of arguments in a function!

Next: Variable Arguments (*args) →


Ready to practice? Try challenges or view solutions


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn