Functions and Parameters

Packaging steps into reusable, named units that take inputs and return outputs.

What is it?

A function is a named block of code that does one job. You define it once and call it whenever you need that job done.

- Parameters are the input names listed in the definition: def greet(name): has the parameter name. - Arguments are the actual values passed in a call: greet("Ada") passes the argument "Ada". - A return value is what the function hands back to the caller. Without an explicit return, Python functions return None and JavaScript functions return undefined. - Default arguments give a parameter a value used when the caller leaves it out: def greet(name, greeting="Hello").

Pure vs side-effecting functions:

- A pure function's result depends only on its arguments, and it changes nothing outside itself. add(2, 3) is always 5. Pure functions are easy to test and reason about. - A function with side effects changes something else: prints, writes a file, modifies a global variable, mutates an argument, or sends a request. Programs need side effects to be useful, but it helps to keep them in a few clearly named places.

The call stack: each call gets its own fresh set of local variables. When a function calls another, the new call is stacked on top; when it returns, it's removed and execution continues where it left off.

Explain like I'm 10

A function is like a coffee machine. You put in inputs (beans, water, a size choice), press the button (call it), and get an output (coffee). You don't need to know how it works inside each time, and you can use it again and again.

Examples

Define, call, return

def area_of_rectangle(width, height):
    return width * height

result = area_of_rectangle(3, 4)
print(result)                    # 12
print(area_of_rectangle(5, 2))   # 10

width and height are parameters; 3 and 4 are arguments. The function computes a value and returns it to the caller.

Defaults, keyword arguments, and the JavaScript equivalent

function greet(name, greeting = "Hello") {
  return greeting + ", " + name + "!";
}

console.log(greet("Ada"));           // "Hello, Ada!"
console.log(greet("Ada", "Welcome")); // "Welcome, Ada!"

// Arrow function: a shorter way to write small functions
const double = (n) => n * 2;
console.log(double(21));              // 42

// Python equivalent with keyword arguments:
//   def greet(name, greeting="Hello"):
//       return f"{greeting}, {name}!"
//   greet("Ada", greeting="Welcome")

Defaults apply when an argument is missing. Python also lets callers name arguments (greeting="Welcome"), which makes calls self-documenting.

Pure vs side-effecting, and Python's mutable-default trap

# Pure: same input, same output, changes nothing else
def with_tax(price, rate):
    return price * (1 + rate)

# Side effect: mutates the caller's list
def add_item(cart, item):
    cart.append(item)

# Trap: the default list is created ONCE, when the function is defined
def add_tag(tag, tags=[]):
    tags.append(tag)
    return tags

print(add_tag("a"))  # ['a']
print(add_tag("b"))  # ['a', 'b']  <- surprise: same list reused

# Fix: use None as the default and create a new list inside
def add_tag_fixed(tag, tags=None):
    if tags is None:
        tags = []
    tags.append(tag)
    return tags

Python evaluates default values once at definition time. A mutable default (list, dict) is shared across calls. JavaScript evaluates defaults on every call, so it doesn't have this trap.

How it works

When you call a function:

1. The arguments are evaluated. 2. A new stack frame is pushed onto the call stack. It holds the function's parameters, local variables and where to return to. 3. The parameters are bound to the argument values. 4. The body runs. Local variables live only in this frame. 5. On return (or the end of the body), the frame is popped and the return value is handed to the caller, which continues from where it paused.

Because each call gets its own frame, a function can be called many times, even recursively, without calls interfering with each other's locals.

Passing arguments: in Python and JavaScript, the parameter refers to the same object the caller passed. Reassigning the parameter inside the function doesn't affect the caller, but mutating a passed list or object does.

If calls nest too deeply (often from runaway recursion), the stack runs out of space: RecursionError in Python, RangeError: Maximum call stack size exceeded in JavaScript.

main() calls total(), which calls with_tax()

  Call stack (top = running now)
  ┌──────────────────────────────┐
  │ with_tax(price=10, rate=0.2) │  ◄── returns 12.0, then popped
  ├──────────────────────────────┤
  │ total(items=[...])           │  ◄── resumes with 12.0
  ├──────────────────────────────┤
  │ main()                       │
  └──────────────────────────────┘

Why does it exist?

Functions let you name an idea, write it once and reuse it. They split big problems into small pieces you can understand, test and fix one at a time. When a bug is fixed inside a function, every caller gets the fix.

When to use it

  • When you'd otherwise copy and paste the same steps.
  • When a block of code does one clear job that deserves a name.
  • To hide details: callers use send_email(to, body) without knowing SMTP.
  • To make logic testable in isolation, especially as pure functions.

When not to use it

- Don't wrap a single obvious line in a function just to have one; it adds indirection without clarity. - Avoid functions that do many unrelated things or take a long list of parameters; split them, or group related parameters into an object. - Avoid hidden side effects in a function whose name suggests it just computes something (get_total shouldn't also save to the database).

Common mistakes

  • Printing a result instead of returning it, so the caller can't use the value (the function returns None/undefined).

  • Forgetting the parentheses: greet refers to the function; greet() calls it.

  • Using a mutable default argument in Python (def f(items=[])), which is shared across calls.

  • Mutating an argument (a list or object) unexpectedly, surprising the caller.

  • Code after a return statement that never runs, or returning from only some branches so others return None.

Practice exercises

  1. Easy:

    Write celsius_to_fahrenheit(c) and fahrenheit_to_celsius(f), and check that converting a value there and back returns the original.

  2. Medium:

    Write format_price(amount, currency="USD", decimals=2) in Python and JavaScript. Call it with only amount, with all arguments, and (in Python) with keyword arguments in a different order.

  3. Hard:

    Take a 30-line script that reads numbers, filters them, computes statistics and prints a report. Split it into small functions, making as many as possible pure. Explain which ones must have side effects and why.

Interview questions

What's the difference between a parameter and an argument?

A parameter is the variable name in the function's definition. An argument is the actual value supplied when calling it.

What is a pure function?

A function whose output depends only on its inputs and that has no side effects: it doesn't modify external state, I/O or its arguments. Calling it with the same arguments always gives the same result.

What is a side effect? Give examples.

Any observable change outside the function's own return value: printing, writing files, network requests, modifying globals, mutating arguments, or reading the current time or a random number.

What does a function return if it has no return statement?

None in Python, undefined in JavaScript.

Explain Python's mutable default argument problem.

Defaults are evaluated once, when the def statement runs. A list or dict default is shared by every call that uses it, so mutations accumulate. Use None as the default and create a new object inside the function.

What is the call stack?

A stack of frames, one per active function call, each holding parameters, locals and the return address. A call pushes a frame; a return pops it. Error stack traces are a printout of this stack.

What causes a stack overflow?

Too many nested calls, usually unbounded recursion without a working base case. Each call adds a frame until the stack's size limit is reached.

If a function modifies a list passed to it, does the caller see the change?

Yes, in Python and JavaScript: the parameter refers to the same list object. Reassigning the parameter to a new list, however, does not affect the caller's variable.

Why do keyword arguments help readability?

resize(image, width=800, keep_aspect=True) explains itself, unlike resize(image, 800, True). They also let callers skip optional parameters and pass arguments in any order.

Scenario: a function `calculate_total` passes all tests alone but gives wrong results in the app. What's a likely cause?

It probably depends on or changes shared state: a global variable, a mutated argument or a mutable default. Making it pure, with all inputs passed in explicitly, typically fixes it and makes the bug obvious.