Default and keyword arguments
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")) # 100Parameters 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 cartThe default is created once, when the function is defined, not on every call. This exact bug is a popular interview question.
In one line
Defaults make parameters optional, keyword arguments make calls readable, and None is the safe default for lists.
Share with a friend