5.1 Functions, Parameters, *args, **kwargs & Default Arg Traps
Stop copy-pasting code! Learn how Python functions work as reusable machines, the difference between print and return, *args/**kwargs, and the infamous mutable default argument bug.
1. What Is a Function? (The Coffee-Machine Analogy)
Think of a function as a coffee machine: you give it inputs (beans + milk = arguments), press start (call the function), and it hands back a result (a hot latte = return value). You don't rebuild the machine every morning — you define it once with def and reuse it anywhere!
def calc_total(price, tax=0.18):
"""Returns final price including tax."""
return price + price * tax
print(calc_total(100)) # 118.0 (uses default tax=0.18)
print(calc_total(100, 0.10)) # 110.0 (overrides default)
print(calc_total(tax=0.05, price=200)) # 210.0 (keyword args — order doesn't matter!)
Fresher Trap #1: print() Inside a Function vs. return
print(x)only writes text to the screen and hands backNone.return xsends the actual value back to the caller so you can store it, add to it, or pass it to another function!
2. Flexible Inputs: *args & **kwargs
What if you want a function that accepts any number of arguments (like print() or max())?
*argscollects extra positional arguments into a tuple.**kwargscollects extra keyword (key=value) arguments into a dictionary.
def sum_all(*args):
return sum(args)
print(sum_all(10, 20)) # 30
print(sum_all(1, 2, 3, 4, 5)) # 15
def build_profile(name, **kwargs):
return {"name": name, **kwargs}
print(build_profile("Riya", role="SDE", city="Pune"))
# {'name': 'Riya', 'role': 'SDE', 'city': 'Pune'}
(Note: The names args and kwargs are just convention — the magic is the * and **!)
3. Fresher Trap #2: Never Use a Mutable Default Argument (bag=[])!
This is one of the most famous Python gotchas — even experienced developers get bitten by it in interviews:
Always default mutable parameters (list, dict, set) to None, and create the fresh object inside the function body:
def add_item(item, cart=None):
if cart is None:
cart = []
cart.append(item)
return cart
print(add_item("tea")) # ['tea']
print(add_item("milk")) # ['milk'] ✓ Fresh list every time!
4. Interactive Trace: Calling a Function & Returning Multiple Values
Quick Quiz: Module 5.1 — Functions & Parameters
Keep Exploring: Related Lessons & Tools
All Courses →Paste any Python, JS, Java, or C++ snippet to estimate Time & Space complexity, or enter input size N to see which algorithms pass in 1s.
Test regular expressions live with color-coded match highlights, capture group inspection, plain-English token breakdown, find-and-replace, and Python/JS snippets.