Programming Fundamentals Questions
Language-agnostic building blocks of writing code: variables, primitive and composite data types, scope and lifetime, functions and callbacks, control flow, and expressions versus statements. Covers the mental model a candidate needs before any language-specific or algorithmic depth. The baseline literacy layer of a technical screen.
Explain what happens mechanically when you write a try/except/finally block (or the equivalent in your language): what runs, in what order, when no exception occurs, when one is raised and caught, and when one is raised and NOT caught. Then walk through handling a file-I/O error inside a function that opens a file, using the construct to guarantee the file is always closed even when an error occurs.
Sample Answer
Direct answer
try marks a block whose exceptions you want to intercept; except runs only if a matching exception is raised inside the try; finally always runs, whether or not an exception occurred and whether or not it was caught, and it runs even if the exception propagates past this block entirely.
Structured elaboration
- No exception: the
tryblock runs to completion, everyexceptclause is skipped, thenfinallyruns. Nothing unusual happens. - Exception raised and caught: execution jumps out of the
tryblock the instant the exception is raised (any code after the raising line intrydoes NOT run), the first matchingexceptclause runs, thenfinallyruns. - Exception raised and NOT caught (no
exceptclause matches its type): the matching-exceptsearch fails,finallystill runs (this is the part people get wrong:finallyis not conditional on being caught), and only afterfinallycompletes does the exception continue propagating up to the caller. - The consequence that matters in practice:
finallyis the correct place for resource cleanup that must happen unconditionally, closing a file handle, releasing a lock, rolling back a partially-started operation, precisely because it is the one block guaranteed to run on every exit path from thetry.
Worked example
def no_exception():
order = []
try:
order.append('try')
except ValueError:
order.append('except')
finally:
order.append('finally')
return order
def caught_exception():
order = []
try:
order.append('try')
raise ValueError('boom')
except ValueError:
order.append('except')
finally:
order.append('finally')
return order
Running both (verified): no_exception() returns ['try', 'finally'] (the except clause never runs), caught_exception() returns ['try', 'except', 'finally']. A third case with a TypeError raised where only ValueError is caught confirms finally still runs before the TypeError propagates out to the caller, exactly as described above.
For the file-I/O case, opening a file and guaranteeing it closes even on a mid-read failure:
def read_lines(path):
f = open(path, 'r')
try:
return f.readlines()
finally:
f.close() # runs whether readlines() succeeds, raises, or the caller's except re-raises
This is exactly what a with open(path) as f: block (or Java's try-with-resources) does under the hood, they are sugar over a try/finally that closes the resource. In this pattern, whether to re-raise the error after logging it or return a sentinel value to the caller depends on whether the caller can meaningfully continue: propagate (let the exception continue, possibly after logging) when the caller cannot proceed without the data; return a sentinel only when the caller has a genuine, documented fallback.
Trade-offs & pitfalls
The most common mechanical mistake is assuming finally only runs when an exception was caught, when in fact it runs on every exit from try (normal completion, caught exception, uncaught exception, even a return inside the try block). The second most common mistake is putting cleanup code after the try/except instead of in finally, which silently skips cleanup on any path that doesn't hit that exact line, exactly the bug that finally exists to prevent.
What is a pure function? Contrast it with a function that has side effects, and give an example of each. Why does purity matter for testability and for safe parallel execution?
Sample Answer
Direct answer
A pure function's output depends only on its inputs, and calling it produces no observable effect outside its own return value, no mutation of external state, no I/O, no reliance on anything that could change between calls. A function with side effects does at least one of those things: it might mutate a variable outside its own scope, write to a file, or return a different result for the same input depending on some external state.
Structured elaboration
- Same input, same output, always: this is the defining property.
math.sqrt(4)is pure, it returns2.0every single time. A function that reads the current time, a global counter, or a mutable default argument that accumulates across calls is not pure, its output can differ across calls even with identical arguments. - No observable effects outside the return value: a pure function doesn't print, doesn't write to a database, doesn't mutate an object passed into it, doesn't increment a counter defined outside itself. If you could delete every call to it (assuming nothing used the return value) and the rest of the program's behavior would be unchanged, that's a strong sign of purity; if deleting a call changes behavior beyond 'the return value is no longer available', something impure happened inside it.
- Why purity matters for testing: a pure function needs no setup beyond its arguments and no teardown, you call it, you assert on the return value, done. An impure function's test has to also arrange whatever external state it reads, and verify whatever external state it mutates, which multiplies both the setup complexity and the number of ways the test can be wrong or flaky.
- Why purity matters for parallel execution: if a function only reads its inputs and produces a return value, calling it concurrently from multiple threads for different inputs is automatically safe, there's no shared mutable state for two calls to race on. An impure function that mutates shared state needs explicit synchronization (locks) to be safe under concurrency, or it will produce wrong results or crashes under load in a way that's notoriously hard to reproduce.
Worked example
def add_tax_pure(price, rate):
return price * (1 + rate) # no side effects
total_calls = {"count": 0}
def add_tax_impure(price, rate):
total_calls["count"] += 1 # side effect: mutates external state
return price * (1 + rate)
Verified: add_tax_pure(100, 0.08) returns 108.0 every time it's called, and calling it twice does not change anything else observable in the program. add_tax_impure(100, 0.08) returns the same 108.0, but after two calls total_calls["count"] has become 2, a change visible to any OTHER code that also reads total_calls, which is exactly the kind of hidden coupling purity avoids: two unrelated pieces of code that both happen to call add_tax_impure now silently affect each other's view of total_calls.
Trade-offs & pitfalls
Purity isn't free, and most real programs need SOME side effects (writing output, updating a database) somewhere; the useful discipline is not 'eliminate all side effects everywhere' but 'push side effects to the edges of the system and keep the core computation (the actual business logic, the actual data transformation) pure', so the large majority of the code gets the testing and concurrency benefits, and the necessarily-impure parts are small, isolated, and easy to reason about individually.
Define the four pillars of object-oriented programming: encapsulation, abstraction, inheritance, and polymorphism. For each, give a short, concrete example in a language of your choice, explain one practical benefit it provides, and name one common pitfall or misuse you have seen.
Sample Answer
Direct answer
The four pillars are encapsulation (bundling data with the methods that operate on it, and hiding internal state behind a controlled interface), abstraction (exposing only what a caller needs, hiding how it's implemented), inheritance (a class reusing and specializing another class's behavior), and polymorphism (code that works against a common interface behaving correctly for many concrete types).
Structured elaboration
- Encapsulation: internal fields are kept private (or convention-marked, e.g. Python's leading underscore) and reached only through methods. Benefit: you can change the internal representation later without breaking every caller. Pitfall: exposing a mutable internal collection directly (a public list field) defeats encapsulation even if the field itself is 'private', because callers can still reach in and mutate it.
- Abstraction: a caller depends on a small, stable surface (an interface, an abstract base class, or just a documented method contract) rather than on implementation detail. Benefit: implementations can be swapped freely. Pitfall: a 'leaky abstraction' that forces callers to know implementation detail anyway (e.g. an interface that only makes sense if you know it's backed by a SQL table).
- Inheritance: a subclass gets a base class's fields and methods and can override behavior. Benefit: real code reuse for a genuine is-a relationship. Pitfall: inheritance used purely for code reuse (not a real is-a relationship) creates fragile coupling, since a change in the base class can silently break every subclass; composition (a class holding an instance of another class instead of inheriting from it) is often the safer default for anything beyond a shallow, genuinely-is-a hierarchy.
- Polymorphism: calling code written against a base type or interface automatically gets the right behavior for whatever concrete subtype is actually passed in, without an if/else on type. Benefit: adding a new type means adding a new class, not editing every call site (this is most of what the 'open/closed' principle (a design should be open to new behavior but closed to editing existing, working code) is about). Pitfall: relying on type-checking (
isinstance) instead of polymorphism reintroduces the very branching the pattern exists to remove.
Worked example
class MetricCollector:
def __init__(self, name):
self._name = name # encapsulation: internal state, reached via methods
self._samples = []
def record(self, value):
self._samples.append(value)
def summary(self):
return f"{self._name}: n={len(self._samples)}"
class LatencyCollector(MetricCollector): # inheritance
def summary(self): # polymorphism: overrides base behavior
if not self._samples:
return f"{self._name}: no samples"
avg = sum(self._samples) / len(self._samples)
return f"{self._name}: avg={avg:.2f}ms over {len(self._samples)} samples"
Calling .summary() on a plain MetricCollector gives "requests: n=2"; calling the exact same method name on a LatencyCollector after recording 12.0 and 18.0 gives "p50_latency: avg=15.00ms over 2 samples" (verified: (12.0 + 18.0) / 2 = 15.00). Code that only knows it has a MetricCollector and calls .summary() gets the right behavior either way, that's the polymorphism.
Trade-offs & pitfalls
The pillars are not equally load-bearing in modern code: encapsulation and abstraction are used constantly and rarely controversial, while deep inheritance hierarchies are increasingly avoided in favor of composition ('composition over inheritance') once a hierarchy goes past one or two levels, because each additional layer makes behavior harder to predict from any single class definition. A senior answer should name that tension rather than presenting a 4-item inheritance-friendly hierarchy as the goal in itself.
Explain the difference between a shallow copy and a deep copy. How does plain assignment differ from copying? Walk through what a shallow-copy utility and a deep-copy utility each do to a nested structure (for example a list of lists), and give a concrete example of a bug that a shallow copy of nested/mutable data can silently cause.
Sample Answer
Direct answer
Plain assignment doesn't copy anything, it just gives a second name to the same object. A shallow copy creates a new outer container but reuses references to the same nested objects inside it, so mutating a nested element through either the original or the shallow copy is visible in both. A deep copy recursively copies every nested object too, giving you a fully independent structure.
Structured elaboration
- Assignment (
b = a):aandbare now two names for the exact same object;b is aisTrue. There is no 'original' versus 'copy', they're the same thing. - Shallow copy (
copy.copy(a), orlist(a), ora[:]for a list): creates a genuinely new outer object (b is ais nowFalse), but for every element that is itself a mutable object (a nested list, a dict, a custom object), the copy holds a reference to the SAME nested object, not a copy of it (b[0] is a[0]isTrue). - Deep copy (
copy.deepcopy(a)): recursively walks the structure and makes a new copy of every nested mutable object too, so nothing is shared (b[0] is a[0]isFalse). - The bug shape this causes: code that shallow-copies a nested structure believing it now has an independent snapshot, then mutates the original, and the 'snapshot' silently changes too, because the shallow copy's nested elements were never actually copied.
Worked example
import copy
original = [[1, 2, 3], [4, 5, 6]]
shallow = copy.copy(original)
deep = copy.deepcopy(original)
original[0].append(999) # mutate a NESTED element of the original
Verified results after that mutation: original == [[1, 2, 3, 999], [4, 5, 6]], shallow == [[1, 2, 3, 999], [4, 5, 6]] (the nested list was shared, so the shallow copy sees the change too), deep == [[1, 2, 3], [4, 5, 6]] (fully independent, unaffected).
A realistic version of this bug: code takes a shallow copy of a dataset as a 'before' snapshot, then runs an in-place normalization pass over the dataset:
def normalize_inplace(rows):
for row in rows:
total = sum(row)
for i in range(len(row)):
row[i] = row[i] / total if total else 0
After running normalize_inplace on the dataset, the shallow-copied 'snapshot' taken beforehand is bitwise identical to the now-normalized dataset (verified by running it: snapshot == dataset evaluates True after normalization), because normalize_inplace mutates each row list in place, and the shallow copy's rows are the SAME row objects as the original's. The 'backup' was never a backup.
Trade-offs & pitfalls
The fix depends on what you actually need: if you truly need an independent snapshot, use copy.deepcopy (accepting its cost, see the mutability discussion) or rebuild the structure by copying each nested piece explicitly. If deep-copying every row of a large dataset is too expensive, the more scalable fix is usually to stop mutating in place at all, have normalize_inplace return a new structure instead of mutating its argument, which sidesteps the shallow/deep copy question entirely by removing the shared-mutable-state pattern that created the risk.
You find a function that catches every exception and silently returns None on any error (a bare except that swallows the failure). What can go wrong with this pattern in production, and what should replace it? Describe the technical fix (which exceptions to actually catch, how to preserve the failure signal) before considering how you'd raise it with the author.
Sample Answer
Direct answer
A bare except: (or except Exception: with a silent return None) doesn't just handle the error you intended, it catches every error that happens to occur in that block and treats all of them identically, so a genuine bug (wrong type, a typo'd attribute, a logic error) gets misclassified as 'expected failure' and hidden from anyone who could act on it. The fix is to catch only the SPECIFIC exception you actually expect, and make failure visible (log it, re-raise it, or return a value the caller is forced to check) instead of silently returning a value indistinguishable from a normal result.
Structured elaboration
- Why this is dangerous, not just untidy:
Noneis frequently also a valid, meaningful return value elsewhere in the codebase. A caller receivingNonefrom this function cannot tell 'there was no data' from 'something crashed while getting the data', those are very different situations that need very different handling, and the swallowed exception has erased the distinction. - Why 'catch everything' is worse than it looks: a bare
exceptcatchesValueError(probably intended) but ALSOTypeError,AttributeError, evenKeyboardInterruptin some forms, errors that indicate a real bug in the calling code, not a data-quality issue the function was designed to tolerate. Narrowing to the specific expected exception type is what lets a genuine bug surface loudly instead of being absorbed by the same catch-all. - What replaces it: catch only the exception type(s) you actually expect and know how to handle; log enough context to diagnose it (what input caused it); then either re-raise (if the caller has no way to proceed without this data) or return an explicit, unambiguous sentinel that cannot be confused with a valid result (not bare
NoneifNoneis otherwise meaningful). - The review conversation: once the technical fix is clear, raising it with the author is a normal, low-friction code-review comment focused on the concrete failure mode ('this will hide a real TypeError as if it were expected'), not a judgment about the person, that's what keeps the fix landing quickly.
Worked example
def bad_parse(raw):
try:
return int(raw)
except Exception:
return None # catches ValueError AND TypeError identically
def good_parse(raw, logger):
try:
return int(raw)
except ValueError:
logger.warning("could not parse %r as int", raw)
raise # or: return a sentinel the caller is forced to check
Verified: bad_parse(None) returns None silently, giving no signal that int(None) actually raised a TypeError (passing None where a string/number was expected, a real bug at the call site, not a data-quality issue). good_parse(None, logger) instead lets that TypeError propagate uncaught (confirmed: it raises TypeError, not swallowed), because the function only catches ValueError. good_parse("not-a-number", logger) correctly logs a warning and re-raises ValueError (confirmed by execution), a case the function WAS designed to handle, with a visible trail.
Trade-offs & pitfalls
The judgment call is choosing between re-raising and returning a sentinel: re-raise when the caller genuinely cannot proceed without valid data (most cases); return an explicit sentinel only when the caller has a real, intentional fallback path for 'this record was unparseable' and the sentinel can't be confused with a legitimate value. What never belongs in either path is catching a broader exception type than you can actually reason about, that's the pattern that turns a narrow, expected failure mode into a general-purpose bug hiding place.
Unlock Full Question Bank
Get access to all 12 Programming Fundamentals interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.