Predict what the function does
Functions questions check arguments, scope and how objects are passed. Getting these right lets you read any Python code base with confidence.
- FlowLoops, else clauses and match statements.
- ArgumentsDefaults, *args, **kwargs, / and *.
- ScopeLEGB, global, nonlocal and closures.
Functions are where Python's flexibility shows: several kinds of arguments, first-class functions, closures and clear scope rules. Interviewers use these questions to see if you can predict what code does — and write functions others can call safely.
1. What does the else clause on a loop do?
A for or while loop can have an else block that runs only when the loop finishes without a break. It is a neat way to write “search and report not found” without a flag variable.
def find_prime_factor(n):
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
print("factor found:", d)
break
else:
print(n, "is prime")
find_prime_factor(97) # 97 is prime2. Explain all the ways to pass arguments to a function.
Positional, keyword, default values, *args (extra positional) and **kwargs (extra keyword). Parameters after * are keyword-only; parameters before / are positional-only. Keyword-only arguments make calls self-documenting, especially for booleans.
def transfer(amount, /, to, *, note="", notify=True):
...
transfer(500, "Ravi", note="rent") # ok
transfer(500, to="Ravi", notify=False) # ok
# transfer(amount=500, to="Ravi") # TypeError: amount is positional-only
# transfer(500, "Ravi", "rent") # TypeError: note is keyword-only3. What is the LEGB rule?
When Python looks up a name it searches four scopes in order: Local (inside the current function), Enclosing (outer functions), Global (module level) and Built-in (len, print…). The first match wins, which is why naming a variable list hides the built-in.
x = "global"
def outer():
x = "enclosing"
def inner():
print(x) # enclosing (found before global)
inner()
outer()4. When do you need global and nonlocal?
Assigning to a name inside a function makes it local. To rebind a module-level name use global; to rebind a name in an enclosing function use nonlocal. Reading does not need either. Prefer returning values or using a class over global — shared mutable state makes code hard to test.
def make_counter():
count = 0
def increment():
nonlocal count # without this: UnboundLocalError
count += 1
return count
return increment
c = make_counter()
c(); c()
print(c()) # 35. What is a lambda and when should you use one?
A small anonymous function limited to one expression. It shines as a short key or callback — sorted(..., key=lambda e: e.salary). If it needs a name, a docstring or more than one expression, write a normal def.
employees = [("Asha", 72000), ("Ravi", 58000), ("Meera", 91000)]
by_salary = sorted(employees, key=lambda e: e[1], reverse=True)
print(by_salary[0]) # ('Meera', 91000)6. How does recursion work in Python and what are its limits?
A recursive function calls itself on a smaller input until it reaches a base case. Python has no tail-call optimisation and a default recursion limit of about 1000 frames, so deep recursion raises RecursionError. Use iteration for deep inputs, or memoise with functools.cache when subproblems repeat.
from functools import cache
@cache
def ways_to_climb(n):
if n <= 1:
return 1
return ways_to_climb(n - 1) + ways_to_climb(n - 2)
print(ways_to_climb(50)) # instant thanks to caching7. Are Python functions first-class objects? What does that allow?
Yes — functions can be stored in variables and data structures, passed as arguments and returned from other functions. This enables callbacks, strategy tables instead of long if-elif chains, decorators and closures.
def gst(amount): return amount * 0.18
def tds(amount): return amount * 0.10
TAXES = {"gst": gst, "tds": tds} # dispatch table
print(TAXES["gst"](1000)) # 180.08. Is Python pass-by-value or pass-by-reference?
Neither exactly — it is pass-by-object-reference (call by sharing). The function receives a reference to the same object. Mutating a mutable argument (appending to a list) is visible to the caller; rebinding the parameter to a new object is not.
def modify(items, number):
items.append(4) # mutates the caller's list
number += 1 # rebinds a local name only
nums, n = [1, 2, 3], 10
modify(nums, n)
print(nums, n) # [1, 2, 3, 4] 10Remember
Key points
- Loop else = no break
Runs only when the loop completes normally.
- Assignment makes a name local
Use nonlocal or global to rebind outer names.
- Call by sharing
Mutations are visible; rebinding is not.
- Recursion limit ~1000
Iterate or memoise for deep inputs.
Interview drill
Follow-up questions
What the interviewer asks after your first answer. Turn on practice mode, answer each one aloud, then reveal.
-
1 What does the match statement do (Python 3.10+)? Intermediate
Structural pattern matching: it matches values and shapes (sequences, mappings, class attributes) and binds parts to names — far more than a switch.
def handle(event): match event: case {"type": "click", "x": x, "y": y}: return f"click at {x},{y}" case {"type": "key", "key": "Enter"}: return "submit" case _: return "ignored" -
2 What is the difference between return and yield? Basic
returnends the function with one value.yieldturns the function into a generator that produces values lazily, pausing between them. -
3 Why does this raise UnboundLocalError: x = 1; def f(): print(x); x = 2? Intermediate
Because
xis assigned insidef, Python treats it as local for the whole function, so the print reads a local that has no value yet. -
4 What are docstrings and how are they used? Basic
The string literal at the start of a function, class or module. It is stored in
__doc__, shown byhelp()and read by documentation tools and IDEs. -
5 What is a higher-order function? Basic
A function that takes or returns another function —
map,sortedwith a key, and every decorator. -
6 How do you return multiple values? Basic
Return a tuple and unpack it:
low, high = min_max(nums). For more than three values, return a dataclass or named tuple for readability.