Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
Default & Keyword Arguments
Default arguments provide fallback values when no argument is passed. Keyword arguments let you specify which parameter gets which value, making function calls more readable.
Default & Keyword Arguments
# Default values
def format_name(first, last, upper=False):
full = f"{first} {last}"
return full.upper() if upper else full
print(format_name("Alice", "Smith")) # Alice Smith
print(format_name("Bob", "Jones", upper=True)) # BOB JONES
# Practical: configurable function
def send_email(to, subject="No Subject", urgent=False):
priority = "⚡ URGENT: " if urgent else ""
print(f"Sending to {to}: {priority}{subject}")
send_email("alice@email.com")
send_email("bob@email.com", "Meeting", urgent=True)
send_email("charlie@email.com", subject="Hello")
# CAUTION: Mutable default arguments (common bug!)
# BAD:
def add_item_bad(item, items=[]):
items.append(item)
return items
# GOOD:
def add_item_good(item, items=None):
if items is None:
items = []
items.append(item)
return items
print(add_item_good("apple")) # ['apple']
print(add_item_good("banana")) # ['banana'] (correct!)Tip
Tip
Use None as default for mutable arguments: def func(items=None): items = items or []. This prevents the shared-list bug.
Functions are first-class objects in Python - pass them, return them, store them
Common Mistake
Warning
def func(items=[]): shares the SAME list across all calls. Each call modifies the same default. Always use None as default for lists/dicts.
Practice Task
Note
(1) Demonstrate the mutable default bug. (2) Fix it using None. (3) Write a function with both required and optional keyword args.