Python · Module 05: Functions & ScopeTutorial 13 of 30

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.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

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!

Visual: A Function Is a Reusable Machine (`return` Sends a Value Back; `print` Only Displays It)
Argumentsprice=100, tax=0.1→def calc_total(price, tax=0.18):return price + price * taxReusable logic — write once, call anywhere!→Return Value110.0Tip: A function without a `return` statement automatically returns `None`!
PYTHON
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 back None.
  • return x sends 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())?

  • *args collects extra positional arguments into a tuple.
  • **kwargs collects extra keyword (key=value) arguments into a dictionary.
PYTHON
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:

Visual: The Famous Python Trap — Never Use `items=[]` as a Default Argument!
✗ Bug: Default List Created ONCEdef add(x, bag=[]): bag.append(x)add(1) → [1]add(2) → [1, 2] !! (Shared bag!)Python creates `[]` at def-time, not call-time!✓ Fix: Use `None` + Create Insidedef add(x, bag=None):if bag is None: bag = []add(1) → [1] | add(2) → [2] ✓Fresh empty list on every call!

Always default mutable parameters (list, dict, set) to None, and create the fresh object inside the function body:

PYTHON
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

Tracing Function Calls, Default Args & Tuple Returns
Interactive Line-by-Line Execution Trace · Step 1 of 5
1→def stats(nums, scale=1):
2 total = sum(nums) * scale
3 return total, total / len(nums)
4s, avg = stats([10, 20, 30], scale=2)
5print(f"Sum={s}, Avg={avg}")
Variables in Memory
stats<function>func
Console Output
(nothing printed yet)
What just happened: Python defines the function object 'stats' in memory — the body does NOT run yet!

Quick Quiz: Module 5.1 — Functions & Parameters

Q1.What does a Python function return if it has NO `return` statement?
Q2.What does `def f(x, a=[]): a.append(x); return a` return on the SECOND call `f(2)` after `f(1)`?
Q3.Inside `def log(*args, **kwargs):`, what are the types of `args` and `kwargs`?

Keep Exploring: Related Lessons & Tools

All Courses →