Testing your own code in an interview

Interview craft Junior Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
def middle(vals: list[int]) -> int:
    return vals[len(vals) // 2]

for case in ([3, 1, 2], [5], []):
    try:
        print(middle(case))
    except IndexError:
        print("IndexError on", case)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 1 5 IndexError on []

Right: the empty case is the one that breaks, which is why it belongs in every test list.

Edge cases such as empty input often fail where the main example passes, so they are worth naming before you finish.

Why not the others?
  • B 1 5 0. Indexing an empty list raises IndexError.
  • C 2 5 IndexError on []. The middle position of [3, 1, 2] holds 1; this function does not sort.

30-second answer

Run the example you agreed at the start, then the edge cases: empty input, one item, all items equal, already sorted or reversed, negative numbers, the largest allowed values and a case with no answer. For each, say the expected output first, then trace or run the code. Finish by restating time and memory complexity.

Practise saying it · 30 s. No recording, just a timer

Explain how you test your solution.

Say your answer out loud, then check which of these points you covered:

  • Agreed example
  • Edge cases from the input
  • Restate complexity

Deep dive

Pick edge cases from the input description, not a fixed list: if values can be negative, test negatives.

If the environment can run code, write a few asserts; if not, dry-run by hand.

A brute-force checker on small random inputs is how this course tests every solution.

Common mistakes

  • Declaring 'done' without running a single case.
  • Only testing the happy path from the question.

Senior take & follow-ups

Say the expected output before running each test; it proves you are testing, not just watching.

Follow-up questions

Think of your answer first, then open the hint.

  1. How do you test when you cannot run code?

    Show hint

    Dry-run two small inputs by hand and walk through each branch.

  2. What is property-based testing?

    Show hint

    Generating many random inputs and checking a property, such as agreeing with a brute-force version.

Suggest a fix if something here is wrong or out of date.