Ravindra BagaleCourses & study guides मराठी Track your progress

Python Functions Tutorial: def, return, Arguments and lambda with Examples

P7.3 Python Function Arguments: Default Values and Keyword Arguments

Why. A tax rate is usually the same, but sometimes different. Defaults keep calls short; keywords keep them clear.

What.

  • Default value — def f(x, rate=0.18): if you skip rate, 0.18 is used.
  • Keyword argument — call with names: f(x=100, rate=0.05).
  • Defaults must come after normal parameters.

How.

Use defaults

  1. Put the common value as the default.
  2. Call without it for the usual case.
  3. Pass a keyword when the case is different.

Worked example A — GST with a default.

Step 1 — What we do. Indian GST is often 18%, sometimes 5%.

Step 2 — Type and run this code.

def with_gst(amount, rate=0.18):
    return round(amount * (1 + rate), 2)

print(with_gst(1000))
print(with_gst(1000, rate=0.05))

Step 3 — Output you should see.

1180.0
1050.0

Step 4 — What it means. No rate → 18%. With rate=0.05 → 5%.

Worked example B — Keyword arguments read clearly.

Step 1 — What we do. A loan EMI-style calculation with named arguments.

Step 2 — Type and run this code.

def simple_interest(principal, rate, years):
    return principal * rate * years

print(simple_interest(principal=50000, rate=0.08, years=3))
print(simple_interest(years=3, rate=0.08, principal=50000))

Step 3 — Output you should see.

12000.0
12000.0

Step 4 — What it means. With names, the order does not matter and the call explains itself. pandas uses keywords everywhere: read_csv(sep=";").

Ravindra Bagale's Tip

When a function has more than two inputs, call it with keyword arguments. Your future self will thank you.