Skip to content
IT Vizag
← Functions & Clean Code

Default and keyword arguments

Lesson 3 of 9 · 1 min read

Make functions flexible and easy to call.

🎬 Video version coming soon — read it now

Two small features make functions much easier to call.

Default values

Give a parameter a default and callers can leave it out:

def ticket_price(age, day="weekday"):
    price = 150 if day == "weekday" else 200
    if age < 12:
        price = price // 2
    return price

print(ticket_price(30))              # 150
print(ticket_price(8, "weekend"))    # 100

Parameters with defaults must come after the ones without. def f(a=1, b) is a SyntaxError.

Keyword arguments

You can pass arguments by name, in any order:

def make_profile(name, city, role):
    return f"{name} | {role} | {city}"

print(make_profile(role="Data Analyst", name="Kavya", city="Vizag"))

Names make calls self-explanatory. Compare these:

send_reminder("Kavya", True, False, 3)
send_reminder("Kavya", sms=True, email=False, days_before=3)

The second one needs no comment.

Built-ins use this too

print("a", "b", "c", sep=" | ", end="!")
sorted(marks, reverse=True)
round(3.14159, ndigits=2)

Now those sep=, end= and reverse= arguments you've already seen make sense: they're keyword arguments with defaults.

The mutable default trap

Never use a list or dictionary as a default:

# Buggy: the same list is shared between calls
def add_item(item, cart=[]):
    cart.append(item)
    return cart

print(add_item("pen"))     # ['pen']
print(add_item("book"))    # ['pen', 'book']  surprise!

# Correct
def add_item(item, cart=None):
    if cart is None:
        cart = []
    cart.append(item)
    return cart

The default is created once, when the function is defined, not on every call. This exact bug is a popular interview question.

Tip: When a function has more than two or three parameters, call it with keyword arguments. Future you will thank you.

In one line

Defaults make parameters optional, keyword arguments make calls readable, and None is the safe default for lists.

Saved on this device. Sign in to keep progress everywhere.

Share with a friend