🐍 Python for Everyone

← Back to challenges

Chapter 10 Interview Prep 21 min read

Interview Questions: Functions Deep Dive

Functions are the single most interview-tested topic in beginner-to-intermediate Python screens — the mutable default argument trap alone shows up constantly, because it separates people who've actually been bitten by it from people who've only read about functions. This set covers parameters vs. arguments, default arguments and their most famous gotcha, *args/**kwargs, scope and why global makes senior engineers wince, closures, how @decorator really desugars, recursion vs. iteration, and the pass-by-object-reference semantics that trip up almost everyone at least once.

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

A parameter is the named placeholder listed in a function's def line — it exists only in the function's definition, before the function is ever called. An argument is the actual value handed in when the function is called and bound to that parameter. In def greet(name): ..., name is the parameter; in the call greet("Ana"), "Ana" is the argument. The two words get used interchangeably in casual conversation, but interviewers listen for whether a candidate knows the distinction is "definition-time placeholder" versus "call-time value."

Using "argument" and "parameter" as if they mean the exact same thing in a context where the distinction matters (e.g. explaining a `TypeError: missing required positional argument`), or being unable to say which one is which when asked directly.

"In def add(a, b=5): return a + b followed by add(3), name the parameters and the arguments." (Parameters: a and b. Arguments: just 3, bound to a — b uses its default since no argument was passed for it.)

2 What does return actually do, and what happens if a function has no return statement at all?

return immediately exits the function and sends a value back to wherever the function was called — any code after a return in that same execution path never runs. A function with no return statement (or a bare return with nothing after it) still returns something: Python implicitly returns None. This is why calling result = some_function() on a function that never explicitly returns anything gives you result == None, not an error — the function ran fine, it just never produced a value on purpose.

Assuming a function without a return statement raises an error or gives back "nothing" in some special sense, rather than the very real, checkable value None.

"What does print(noop()) output, given def noop(): pass?" (None — no explicit return means Python returns None automatically.)

3 What is the mutable default argument trap, and why does it happen?

A default argument value is created exactly once, when the def statement itself runs — not fresh on every call. That's harmless for immutable defaults like 5 or "x", but if the default is a mutable object like [] or {}, every call that doesn't supply its own argument shares that same list or dict, and mutations from one call leak into the next. def add_item(item, basket=[]): basket.append(item); return basket looks like it should return a fresh one-item list each time, but calling it twice with no basket argument returns ["apple", "banana"] the second time, not ["banana"] — the same list object stuck around between calls. The standard fix is to default to None and create the mutable object fresh inside the function body: def add_item(item, basket=None): basket = [] if basket is None else basket; ....

Using a mutable literal ([], {}, set()) directly as a default argument in real code without knowing this trap exists — it's one of the most common real bugs in production Python, not just a trivia question.

"Given def add_item(item, basket=[]): basket.append(item); return basket, what does calling add_item('apple') then add_item('banana') return the second time?" (['apple', 'banana'] — both calls shared the same default list.)

4 What's the difference between a positional argument and a keyword argument?

A positional argument is matched to a parameter purely by its order in the call — the first value goes to the first parameter, the second to the second, and so on. A keyword argument is passed as name=value and matched by that name regardless of order, which makes the call self-documenting and lets arguments be supplied out of order. greet("Ana", 30) relies on position; greet(age=30, name="Ana") is identical in effect but reads more clearly at the call site and is safer once a function has several parameters, since it's immune to accidentally swapping two same-typed arguments.

Mixing them incorrectly — Python requires all positional arguments to come before any keyword arguments in a call, so greet(name="Ana", 30) is a SyntaxError.

"Is greet(30, name='Ana') valid if greet is defined as def greet(name, age): ...?" (No — 30 would bind positionally to name first, then name='Ana' tries to bind the same parameter again, raising TypeError: got multiple values for argument 'name'.)

5 What do *args and **kwargs actually do, and when would you reach for each?

*args collects any number of extra positional arguments into a tuple inside the function, and **kwargs collects any number of extra keyword arguments into a dict. def total(*args): return sum(args) can be called as total(1, 2, 3) or total(1, 2, 3, 4, 5) with no need to predefine how many numbers are coming. Reach for *args when a function needs to accept a variable number of similar, unnamed values (like numbers to sum, or items to log); reach for **kwargs when it needs to accept an open-ended set of named options (like configuration settings) without hard-coding every possible one. The names args and kwargs are just convention — the * and ** are what actually matter to Python.

Believing *args and **kwargs must be named exactly that (any name works, the stars do the work), or using them everywhere "just in case" instead of writing explicit named parameters when the function's inputs are actually well-known and fixed.

"What does total(1, 2, 3, 4) return, given def total(*args): return sum(args)?" (10 — all four positional arguments land in the args tuple, then get summed.)

6 What's the difference between local scope and global scope, and why is using the global keyword often considered bad practice?

Local scope is the set of names that exist only inside the function where they were created — they disappear once the function returns, and nothing outside can see them. Global scope is the module-level namespace, visible from anywhere in the file, including inside functions (functions can read a global variable with no special keyword at all). The global keyword is only needed when a function wants to reassign a global variable rather than just read it, and it's considered risky because it makes a function's behavior depend on, and silently mutate, state that lives outside its own inputs and outputs — two different functions touching the same global can produce order-dependent, hard-to-trace bugs, especially as a codebase grows. The safer default is to pass values in as parameters and get results back via return, keeping each function's behavior self-contained and predictable.

Reaching for global as the default way to share state between functions instead of passing parameters and returning values, or not realizing that reading a global inside a function needs no global keyword at all — only reassigning it does.

"Given count = 0 at module level and def bump(): global count; count += 1, what is count after calling bump() three times?" (3 — each call reassigns the actual global thanks to the global declaration.)

7 What does nonlocal do, and how is it different from global?

nonlocal lets a nested (inner) function reassign a variable that belongs to its enclosing function's local scope — one level up, but still not the module-level global scope. global reaches all the way up to module level; nonlocal only reaches the nearest enclosing function that actually has that variable. This matters specifically for closures: a counter-style closure where an inner function increments a variable defined in the outer function needs nonlocal to modify that outer variable, because without it, the inner function would just create a brand-new local variable of the same name instead of touching the outer one.

Using global when the variable being modified actually lives in an enclosing function, not at module level — that's a SyntaxError (or worse, silently modifies an unrelated module-level variable of the same name if one happens to exist).

"Given a closure where inner() does count += 1 on a variable from its enclosing function, with no nonlocal declaration, what happens?" (An UnboundLocalError — without nonlocal, Python treats count as a brand-new local variable inside inner, and count += 1 tries to read it before it's ever been assigned.)

8 What is a closure, and what's a concrete use case for one?

A closure is an inner function that "remembers" and can still use variables from its enclosing function's scope, even after that enclosing function has already finished running and returned. def make_multiplier(factor): def multiplier(x): return x * factor; return multiplier returns the inner multiplier function, and every time it's later called, it still has access to whatever factor was when it was created — double = make_multiplier(2) then double(5) gives 10, and a separate triple = make_multiplier(3) keeps its own independent factor. A concrete real use case: building several specialized functions from one factory function (a multiplier, a validator with a fixed threshold, an event handler that remembers which button created it) without needing a full class just to hold that one piece of remembered state.

Confusing a closure with just "a nested function" — the defining feature is that it captures and retains access to the enclosing scope's variables after that scope has finished executing, not merely that one function is defined inside another.

"Given double = make_multiplier(2) and triple = make_multiplier(3) from the factory above, what does double(5) return, and does calling it affect triple?" (10, and no — each closure keeps its own independent copy of factor from when it was created.)

9 Why do decorators exist, and what problem are they solving?

A decorator lets you add behavior "around" a function — logging, timing, access checks, retry logic, result formatting — without editing that function's own body or repeating the same wrapping code above every function that needs it. The problem it solves is code duplication: without decorators, adding "log every call to this function" to ten different functions means pasting the same logging code into all ten; with a decorator, that logic is written once and applied with a single @decorator_name line above each function definition. It's the same instinct as a comprehension replacing a repetitive loop — capturing a repeated pattern once and applying it declaratively wherever it's needed.

Treating a decorator as mysterious "magic syntax" rather than what it actually is underneath: a function that takes a function and returns a (usually wrapped) function.

"You have five functions that should each print how long they took to run. What's the decorator-based fix versus the copy-paste fix?" (Write one timing decorator once and put @timer above each of the five functions, instead of pasting the same timing code inside all five function bodies.)

10 How does @decorator syntax actually desugar, and what does that reveal about how decorators work?

Writing @shout directly above def greet(name): ... is exactly equivalent to defining greet normally and then immediately running greet = shout(greet) right after — the @ syntax is pure sugar for "pass this function into that one, and replace the original name with whatever comes back." This reveals that a decorator is just a regular function that accepts a function as its argument and returns a (typically new, wrapping) function; there's no special runtime magic beyond ordinary function calls and reassignment. Because of this, a hand-written decorator almost always defines an inner wrapper function that calls the original, does something before/after/around that call, and returns wrapper itself as the replacement.

Being unable to write out the desugared, non-@ version of a decorated function by hand — if the @decorator line is genuinely mysterious rather than "sugar for a reassignment," that's a sign the concept hasn't clicked yet.

"Given @shout above def greet(name): return f'hello {name}', write the equivalent code without using @ syntax at all." (def greet(name): return f'hello {name}' followed by greet = shout(greet) — identical behavior, no @ needed.)

11 Why does a decorator's inner wrapper function usually accept *args, **kwargs?

A decorator is often written once and applied to many different functions, and those functions may take completely different parameter signatures — one might take zero arguments, another might take three positional arguments, another might take keyword arguments. If the wrapper hard-codes specific parameter names, the decorator only works on functions matching that exact signature. Writing def wrapper(*args, **kwargs): result = func(*args, **kwargs); return result lets the wrapper transparently accept whatever the decorated function itself accepts, and pass all of it straight through unchanged — making the decorator reusable across any function regardless of its parameter list.

Writing a wrapper with fixed, named parameters, which quietly breaks the moment the decorator is applied to a function with a different signature than the one it was first tested against.

"Why would a decorator's wrapper defined as def wrapper(x): return func(x) * 2 fail if applied to a function that takes two arguments?" (Calling the decorated function with two arguments would raise a TypeError, since wrapper itself only accepts one — *args, **kwargs avoids hard-coding an arity the wrapper doesn't actually need to know.)

12 What's the tradeoff between recursion and iteration, and what's the practical risk of using recursion?

Recursion solves a problem by having a function call itself on a smaller version of the same problem until it hits a base case that stops the calls; iteration solves the same class of problem with a loop. Recursion often reads more naturally for problems that are inherently defined in terms of themselves — factorial, tree/nested-structure traversal, some search algorithms — while iteration is usually more efficient in Python specifically, since each recursive call adds a new frame to the call stack, and Python has no built-in tail-call optimization to collapse that overhead away. The practical risk is a stack overflow (RecursionError in Python): recurse too deep — thousands of calls without hitting the base case — and the program crashes, whereas an equivalent loop just keeps iterating with flat, constant memory use.

Reaching for recursion on a problem with a very large or unbounded depth (e.g. processing a million-item list one at a time recursively) when a simple loop would do the identical job without any risk of hitting Python's recursion limit.

"Given def factorial(n): return 1 if n <= 1 else n * factorial(n - 1), what happens if you call factorial(10000)?" (It raises a RecursionError — the call stack overflows long before reaching the base case, since Python's default recursion depth limit is far lower than 10,000.)

13 Every recursive function needs a base case — what happens without one, and what else does a correct recursive function need?

A base case is the condition under which a recursive function stops calling itself and returns a direct answer instead — without one, the function calls itself forever (or until it hits Python's recursion limit and raises RecursionError), since there's never a point where it stops. A correct recursive function needs exactly two things: a base case that can be reached, and a recursive case that always moves closer to that base case with each call — usually by shrinking the input in some way (n-1, a smaller slice, one fewer item left to process). factorial(n)'s base case is n <= 1, returning 1 directly, and its recursive case, n * factorial(n - 1), always calls itself with a strictly smaller n, guaranteeing it eventually reaches the base case.

Writing a recursive call that doesn't actually shrink the problem toward the base case (e.g. accidentally calling factorial(n) instead of factorial(n - 1)) — that's infinite recursion even though a base case technically exists in the code, because it's never actually reached.

"What's wrong with def countdown(n): print(n); countdown(n - 1) if it's meant to stop at zero?" (There's no base case at all — it never checks for n == 0 and returns, so it keeps recursing into negative numbers until it hits a RecursionError.)

14 Why does mutating a list argument inside a function affect the caller's original list, but reassigning that same parameter doesn't?

Python passes arguments by object reference: the parameter inside the function becomes another name pointing at the exact same object the caller passed in, not a separate copy of it. Because of that, any mutation performed through that parameter — lst.append(1), lst[0] = 99 — changes the one shared object in place, so the caller sees the change too. But reassigning the parameter itself, lst = [9, 9], doesn't mutate anything; it just points the local name lst at a brand-new object, leaving the caller's original object completely untouched, because the caller's variable was never pointing at the parameter name to begin with, only at the same object the parameter name also happened to reference. This is why def mutate_list(lst): lst.append(99) changes the caller's list, while def reassign_list(lst): lst = [1, 2, 3] has zero effect on it.

Describing Python as strictly "pass by reference" (implying reassignment would also affect the caller, like some other languages' reference parameters) or strictly "pass by value" (implying mutation wouldn't affect the caller either) — neither label is accurate; "pass by object reference" is the precise description.

"Given data = [0], what is data after calling def append_one(lst): lst.append(1) as append_one(data)? What if the function instead did lst = [9, 9]?" (Mutation case: data becomes [0, 1] — the caller's list itself was changed. Reassignment case: data stays [0] — the parameter was pointed at a new object, but the caller's variable never followed along.)

Rapid-Fire Review

Quick recall check — fill in each blank and hit Check.

🎉 Perfect score — you're ready to talk about this chapter in an interview.
← Challenges Build the Project →