Thinking Aloud, Clarifying and Writing Clean Python
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A correct idea in your head scores nothing. These habits turn it into an answer an interviewer can follow and trust.
Think aloud, in six steps
Thinking aloud means saying your reasoning as you work: what you understand, what you try, why you change your mind. It lets the interviewer follow you, and lets them give a hint instead of watching you stall.
Silence hides your thinking, and the interviewer can only score what they can hear. Follow the same six steps on every question and talk through each one.
sentence = "to be or not to be"words = sentence.split()print(len(words))Example 1 · Thinking aloud on a small question
Question: "Count the words in a sentence."You: "So the input is one string and I return a whole number. Can there be extra spaces, or an empty string?"Her: "Yes to both."You: "Then split() with no argument is enough, because it skips extra spaces. For an empty string it gives an empty list, so the count is 0. I will try "to be" and "" to check that."Restate, clarify, example, approach: all spoken before one line of code.
What this code does
- The questions are short and the answers change the code: extra spaces and an empty string both shape the plan.
- Ending with two test inputs promises the test step, so the interviewer already knows what to expect.
Even this tiny program has a story to tell: "split() with no argument cuts on any run of spaces, so the count is the length of the list." Short sentences like that are enough.
Clarify before you code
A clarifying question is a short question that removes doubt about the input, output or limits before you write code, such as whether the list can be empty or contain repeated values.
Most questions leave something open. Ask short questions about the input, the output and the limits, then write the answers down.
def top_scorer(scores): """Name with the highest mark; None if empty; first one on a tie.""" if not scores: return None return max(scores, key=scores.get)Example 2 · Agreeing the rules, then coding them
def top_scorer(scores): """Name with the highest mark; None if empty; first one on a tie.""" if not scores: return None return max(scores, key=scores.get)
print(top_scorer({"Meera": 88, "Arjun": 92, "Tara": 92}))print(top_scorer({}))Arjun None
What this code does
- Two choices were clarified: what to return for no students and what to do on a tie. Arjun comes first in the dictionary, so Arjun is returned.
- If you had not asked, you might code a different rule and only learn it from a failing test.
The docstring records what was agreed. max(scores, key=scores.get) compares the dictionary's keys by their marks, and it returns the first of equal highest marks.
Clean Python on a whiteboard or shared editor
Clean code uses clear names, small functions and simple control flow, so another person can read it once and understand it. It matters in interviews because the interviewer reads while you write.
The interviewer reads your code as you write it. Clear names and small steps let them follow, and they make your own mistakes easier to spot.
def average_passing(marks, pass_mark=40): passing = [m for m in marks if m >= pass_mark] return sum(passing) / len(passing) if passing else 0.0Example 3 · Messy and clean, same answer
def f(l): s=0;c=0 for x in l: if x>=40: s+=x;c+=1 return s/c if c else 0.0
def average_passing(marks, pass_mark=40): passing = [m for m in marks if m >= pass_mark] return sum(passing) / len(passing) if passing else 0.0
print(f([35, 80, 62, 20]))print(average_passing([35, 80, 62, 20]))71.0 71.0
What this code does
- Both print the average of the marks that reached 40. Only one can be read at a glance.
- Names such as
passingandpass_markreplace the comments the messy version would need. A magic number like 40 becomes a named argument.
Write the function name and arguments first, then the steps. Indentation is part of Python, so keep four spaces and leave room between lines on a board. Do not worry about exact imports; say which one you would use.
Dry run, then say the cost
A dry run is tracing your code by hand on a small input, line by line, writing down the value of each variable, to find mistakes without running anything.
Before you say done, trace your code by hand on a small input, writing down each variable. Then state the time and space cost in plain words.
total = 0for step, mark in enumerate([70, 55, 90], start=1): total += mark print(f"step {step}: total {total}")Example 4 · Dry run as a trace
marks = [70, 55, 90]total = 0for step, mark in enumerate(marks, start=1): total += mark print(f"step {step}: add {mark} -> total {total}")print("average:", round(total / len(marks), 1))step 1: add 70 -> total 70 step 2: add 55 -> total 125 step 3: add 90 -> total 215 average: 71.7
What this code does
- Each printed line is what you would write on the board: the step, the value read and the running total.
- The average is 71.7 (rounded), which you can check by hand: 215 divided by 3.
A dry run finds the bug before the interviewer does. After it, say something like: "One pass over the list, so time grows in step with its length, and I keep only a total, so space is constant."
Next step
Check your understanding
10 quick questions