Best Coding Practices and Effective Code Review

Who is this lesson for?

Students and developers who can already write code and want better readability, testing, and team code-review habits. The focus is making a working solution understandable and changeable by someone else.

Basic Python. Advanced algorithms and previous code-review experience are not required; the Git exercise explains its setup separately.

Purpose of this lesson

Write readable solutions with meaningful names, small coherent functions, consistent layout, and useful comments.

Explain and check the reasoning in the original algorithm examples, including the boundaries that can break them.

Use tests, focused changes, and constructive code review to make team changes safer.

Before you start

Basic Python functions, loops, lists, dictionaries, and conditionals. A stack and tree recursion are explained when introduced. Reading requires no installation; running the workshop requires Python 3, a terminal, and the documented dependencies. The optional Git exercise requires Git; check git --version before starting it. It provides a separate practice folder and explains staging.



Best Coding Practices and Effective Code Review

How do you turn a working solution into code that you, an interviewer, and a teammate can understand and change?

This lesson is about the way you write and review code after you have an idea for a solution. A correct algorithm can still be difficult to read, awkward to test, or risky to change. Naming, function boundaries, layout, and comments make that idea visible to another person.

We begin with coding-interview examples: palindromes, hourglass sums, brackets, containers, and trees. Then we carry the same habits into team work: focused changes, tests, pull requests, and useful review conversations. You do not need to know these algorithms already; each example explains the problem before examining the code.

A small example: do the brackets close correctly?

A bracket checker receives text made only of round (), square [], and curly {} brackets. It returns True if every opening has the right closing bracket in the right order, and False otherwise. For example, () is valid: the round bracket opens and then closes.

Valid example: ([]). Read left to right. First ( opens a round pair; then [ opens a square pair inside it. Next ] closes that square pair; finally ) closes the outer round pair. The result is True. When one pair is opened inside another, the inner pair must close first.

Invalid example: ([)]. The first two characters again open a round pair and then a square pair. But the third character is ): it tries to close the outer round pair while the inner square pair is still open. At that point we need ], not ). The result is False. Every type has an opening and a closing, but their order is wrong.

Now connect this to code quality. The function must return the right result, and its names and conditions should help a reader see how it makes that decision. A successful test on () alone tells us neither that all bracket patterns work nor that the implementation is easy to understand. No stack or algorithm knowledge is needed for this first example.



Try it yourself

Is returning True for () enough to trust this checker? Choose another input and explain its expected result. If you wish, also describe how you would check the brackets.





Show a worked solution

No. For example, ([]) is valid because the inner square pair closes before the outer round pair, so it should return True. ([)] has the wrong order and should return False. One correctly explained additional example is enough for this question.

If you also describe an algorithm, keeping openings on a stack and matching each closing to the latest opening is a valid approach. Matching means a corresponding pair such as ( and ), not identical characters. For example, the one-character input ) has a closing with no opening: the stack is empty, so reject it before popping. No opening may remain when reading ends. This is one optional approach, not a requirement to write an algorithm.



Treating code quality as decoration that can wait until after the code becomes difficult to change.



Good habits make you faster

The point of readable code is to spend less time guessing, debugging, and explaining the same thing again.

There are four practical reasons for best practices: speed, fewer bugs, concise code, and readability. These reinforce one another when a name removes ambiguity or a helper makes a complicated operation easy to inspect. They are not a contest to write the fewest characters.

In an interview, you have to explain a solution while implementing it. At work, someone else may need to fix it months later. Both readers benefit when the code exposes its purpose and its assumptions. Clear code does not prove the algorithm correct, but it makes incorrect reasoning easier to find.

Shorter is not always clearer

Both functions below calculate the same triangular number for a non-negative integer n. The second makes the two factors visible. A reader still needs to know why n times n + 1 is divided by two; that mathematical explanation belongs in your reasoning, not in a clever variable name.

def f(n):
    return n * (n + 1) // 2

def sum_first_numbers(count):
    next_number = count + 1
    return count * next_number // 2

assert sum_first_numbers(4) == f(4) == 10
assert sum_first_numbers(0) == 0

Try it yourself

Does replacing a ten-line function with one dense line necessarily improve its quality? Explain your decision.





Show a worked solution

No. Compare the behavior, the assumptions a reader must remember, and how easily each branch can be tested. A shorter version helps if it removes repetition without hiding the rule. If it combines unrelated steps or hides a boundary case, the longer version may be clearer.



Confusing concise code with compressed code.



Names should reveal what a value means

A palindrome reads the same in both directions. We will ignore punctuation and letter case in this ASCII-text example.

For example, A man, a plan, a canal: Panama becomes amanaplanacanalpanama and should return True. The name text explains the input, normalized explains the transformed string, and left and right describe positions. A variable named l can be mistaken for the digit 1; short names are useful only when they stay unambiguous.

Change one thing at a time when comparing versions. Below, normalization and the two-pointer algorithm stay fixed so you can judge the names themselves without confusing a rename with an algorithm change. Normalization uses O(n) additional space; readable names do not reduce that cost.

Here n is the number of input characters. O(n) space means storage can grow in proportion to n; O(1) means a fixed amount independent of input size. This notation describes growth, not an exact number of bytes or seconds.

A palindrome checker with meaningful names

After normalization, the pointers move inward. A mismatch returns False immediately; crossing the pointers means every pair matched. Empty normalized text returns True under this exercise’s definition.

# Before: the same algorithm, with ambiguous names.
def palindrome_before(s):
    s = "".join(c.lower() for c in s if c.isalnum())
    l, r = 0, len(s) - 1
    while l < r:
        if s[l] != s[r]:
            return False
        l += 1
        r -= 1
    return True

# After: names reveal the same decisions.
def is_palindrome(text):
    normalized = "".join(
        char.lower() for char in text if char.isalnum()
    )
    left, right = 0, len(normalized) - 1
    while left < right:
        if normalized[left] != normalized[right]:
            return False
        left += 1
        right -= 1
    return True

assert is_palindrome("A man, a plan, a canal: Panama")
assert not is_palindrome("race a car")
assert is_palindrome("!!!")
for sample in ("A man, a plan, a canal: Panama", "race a car", "!!!"):
    assert palindrome_before(sample) == is_palindrome(sample)

Try it yourself

Suggest names for s, l, and r. If you rename l in the definition but not in the comparison, what happens?





Show a worked solution

text or normalized_text, left or left_index, and right or right_index are reasonable. Update every use of a renamed variable. A leftover name may raise NameError, or accidentally read a different existing variable. Renaming is not permission to change which characters the function accepts.



Treating a naming improvement as an algorithmic optimization.



Make a helper correspond to a real step

An hourglass in a grid contains three cells on top, one in the middle, and three on the bottom.

Calculating one hourglass and searching the whole grid are separate jobs. That is a useful boundary: you can verify the seven-cell formula without also reasoning about two nested search loops. A helper earns its place by naming a step of the solution, not merely by reducing line count.

The input here is a rectangular integer grid with at least three rows and three columns. For each top-left position, calculate one candidate sum and compare it with the best so far. Do not add neighboring hourglass sums together; they are competing candidates. Initialize the maximum from a real candidate so all-negative grids work.

One calculation, then a search

Take a grid with rows [1, 2, 3, 4], [0, 5, 6, 0], and [7, 8, 9, 10]. At the left position, select top cells 1, 2, 3; middle cell 5; and bottom cells 7, 8, 9. Their sum is 1 + 2 + 3 + 5 + 7 + 8 + 9 = 35. Shift one column right: 2 + 3 + 4 + 6 + 8 + 9 + 10 = 42. We want the larger single sum, 42, not 35 + 42 = 77.

For a 3 by 4 grid there are two candidate hourglasses. The helper receives grid, top, and left explicitly. For fixed-size hourglasses, each helper call is O(1), so the whole search is O(rows × columns).

def hourglass_sum(grid, top, left):
    top_sum = sum(grid[top][left:left + 3])
    middle = grid[top + 1][left + 1]
    bottom_sum = sum(grid[top + 2][left:left + 3])
    return top_sum + middle + bottom_sum

def max_hourglass_sum(grid):
    best = hourglass_sum(grid, 0, 0)
    for top in range(len(grid) - 2):
        for left in range(len(grid[0]) - 2):
            best = max(best, hourglass_sum(grid, top, left))
    return best

assert hourglass_sum([[1]*3, [1]*3, [1]*3], 0, 0) == 7
assert max_hourglass_sum([[-1]*4 for _ in range(3)]) == -7

Try it yourself

Every cell in a 3 by 3 grid is -1. What is its only hourglass sum, and what wrong answer would best = 0 preserve? Give one input and expected result for testing hourglass_sum separately from the search.





Show a worked solution

The seven selected cells sum to -7. A maximum initialized to 0 would remain 0, even though no hourglass has that sum. Starting with the first actual candidate gives -7. A separate helper check is hourglass_sum([[1, 1, 1], [1, 1, 1], [1, 1, 1]], 0, 0) == 7: it checks the seven-cell calculation without a search loop.



Extracting a helper while leaving a wrong accumulation or initial value untouched.



Layout should expose the control flow

In Python, indentation determines which statements belong to a branch or loop. Line breaks inside parentheses help the reader see the same structure.

Use a consistent indentation convention; Python’s style guide recommends four spaces per block. Put long conditions in parentheses and arrange their parts so a reader can check one condition at a time. Indentation is not just visual in Python: moving a return can change the result.

Compare a compressed grid check with a condition laid out one part at a time. Here, inside_grid means that both coordinates are inside a rectangular grid. Check that the grid has a row before reading grid[0]. Python’s and evaluates left to right and stops at the first false condition, so the empty grid is safe.

Make the boundary checks visible

For a 2 by 3 grid, row 1 and column 2 are valid. Row 2 is outside. Each line is one condition; the last line does not run when grid is empty.

# Before: the conditions are correct but crowded onto one line.
def inside_grid_compact(grid, row, column):
    return bool(grid) and 0 <= row < len(grid) and 0 <= column < len(grid[0])

# After: preserve the evaluation order while exposing each condition.
def inside_grid(grid, row, column):
    return (
        bool(grid)
        and 0 <= row < len(grid)
        and 0 <= column < len(grid[0])
    )

assert inside_grid([[0]*3 for _ in range(2)], 1, 2)
assert not inside_grid([[0]*3 for _ in range(2)], 2, 0)
assert not inside_grid([], 0, 0)
for grid, row, column in (([], 0, 0), ([[0]*3]*2, 1, 2), ([[0]*3]*2, 2, 0)):
    assert inside_grid_compact(grid, row, column) == inside_grid(grid, row, column)

Try it yourself

For inside_grid([], 0, 0), which expression stops evaluation before grid[0] is read? What would happen if 0 <= column < len(grid[0]) were evaluated first?





Show a worked solution

bool(grid) is False for [], so and stops and the function returns False without reading grid[0]. If the column expression is evaluated first, reading the nonexistent first row grid[0] raises IndexError. The same checks can behave differently when their evaluation order changes.



Reformatting a condition without checking evaluation order or the indentation of return.



Comments should explain a non-obvious choice

A useful comment tells the reader why a step is necessary. It does not narrate every assignment.

Focus on the comment’s job: it should explain why the right operand is removed first. The subtraction trace below is enough to judge that comment; you can return to the complete evaluator after this exercise.

A stack stores values so the most recently added value is removed first. In Python a list can do this: append adds to the top and pop removes from it. In postfix notation the operator follows its operands: 7 3 - means 7 minus 3. The right operand is popped first because it was pushed last. This order is worth explaining; a comment saying pop from stack adds little.

Integer division needs another explicit rule. This exercise truncates toward zero: -7 divided by 3 becomes -2. Python’s // rounds down instead, producing -3. Using integer magnitudes and restoring the sign avoids both that mismatch and the precision loss that converting very large integers to float can introduce.

Document the rule that Python does not supply automatically

The helper below implements just the division step. It assumes integer operands and deliberately raises ZeroDivisionError for a zero divisor. A complete postfix evaluator would also validate tokens and stack size; this helper is not that whole program.

stack = [7, 3]
right = stack.pop()
left = stack.pop()
stack.append(left - right)
assert stack == [4]

def divide_toward_zero(left, right):
    if right == 0:
        raise ZeroDivisionError("division by zero")
    # // rounds down; the expression language truncates toward zero.
    magnitude = abs(left) // abs(right)
    return -magnitude if (left < 0) != (right < 0) else magnitude

assert divide_toward_zero(-7, 3) == -2
assert divide_toward_zero(7, -3) == -2
assert divide_toward_zero(-7, -3) == 2

Try it yourself

Write a useful one-sentence comment for the order of two stack pops in a subtraction operation.





Show a worked solution

For example: The right operand is on top of the stack, so pop it first and compute left minus right. The comment explains why reversing the assignment would turn 7 - 3 into 3 - 7.



Adding comments to unclear code instead of first improving its names and structure.



Readable interfaces reduce hidden work

A prefix sum stores running totals so repeated range-sum queries do not have to add the same values again.

Read this as an interface review: can a caller tell which endpoints are included and where the one-time preparation belongs? Calculate the two requested ranges first, then use the class to check that those decisions are visible.

The input values and the query indices in this example are integers. For [2, -1, 4], store prefix totals [0, 2, 1, 5]. The sum from start up to, but excluding, end is prefix[end] minus prefix[start]. The leading zero removes a separate start-at-zero case. These boundaries are part of the interface and must be stated.

Separate construction from queries: construct once in O(n), then answer each query in O(1). A method that rebuilds the totals on every query does unnecessary work. In the class below, __init__ runs when PrefixSums(values) creates an object. self.prefix stores that object’s totals so later range_sum calls can reuse them.

A small class with one stated interval convention

Build the totals explicitly: start at 0, add 2 to get 2, add -1 to get 1, then add 4 to get 5. That gives [0, 2, 1, 5]. Array positions start at zero: values[1] is -1 and values[2] is 4. range_sum(1, 3) includes those two positions and stops before position 3, so prefix[3] - prefix[1] = 5 - 2 = 3.

range_sum(1, 3) includes -1 and 4, so the result is 3. range_sum(0, 0) returns 0 for an empty range. For integer indices, an out-of-bounds or reversed range raises ValueError. Non-integer indices are outside this example’s contract.

class PrefixSums:
    def __init__(self, values):
        self.prefix = [0]
        for value in values:
            self.prefix.append(self.prefix[-1] + value)

    def range_sum(self, start, end):
        if not 0 <= start <= end < len(self.prefix):
            raise ValueError("invalid half-open range")
        return self.prefix[end] - self.prefix[start]

sums = PrefixSums([2, -1, 4])
assert sums.range_sum(1, 3) == 3
assert sums.range_sum(0, 0) == 0

Try it yourself

What should range_sum(0, 3) and range_sum(2, 2) return for [2, -1, 4]? Why should you build the object outside a loop of queries?





Show a worked solution

They return 5 and 0. Constructing once costs O(n), then q queries cost O(q), for O(n + q) total. Rebuilding inside the query loop can cost O(n × q). The class name alone does not guarantee that callers use it efficiently.



Calling an interface clearer without stating whether the end index is included.



Track the totals you have already seen

To find a nonempty contiguous range with a target sum, remember the totals seen before each position.

Here the names and statement order must make the stored information clear. Trace the one-element inputs in the exercise first: they reveal whether seen_totals means earlier totals or includes the current one. You can revisit the longer range example afterward.

Values and target are integers in this example. Prefix totals can also tell us whether any contiguous range has a chosen sum. If the current running total is current and an earlier total was previous, the intervening range sums to current - previous. We need an earlier total equal to current - target.

Initialize seen with zero so a range starting at the first element can match. Check before adding the current total so target zero does not match an empty range automatically. The set remembers totals, not individual array values. The algorithm takes expected O(n) time with a hash set and O(n) extra space. A set remembers unique values: {0} starts with one stored total and add inserts another. Membership asks whether a total has appeared, without scanning every earlier total.

Trace a negative number and a zero target

For [2, -1, 4] and target 3, totals progress 2, 1, 5. At 5, the earlier 2 exists, so the range [-1, 4] sums to 3. For [5] and target 0 there is no nonempty match; adding 5 before checking would falsely match the current total against itself.

def contains_target_sum(values, target):
    seen_totals = {0}
    current_total = 0
    for value in values:
        current_total += value
        if current_total - target in seen_totals:
            return True
        seen_totals.add(current_total)
    return False

assert contains_target_sum([2, -1, 4], 3)
assert contains_target_sum([0], 0)
assert not contains_target_sum([5], 0)
assert not contains_target_sum([], 0)

Try it yourself

seen_totals starts as {0}. For target 0, explain why [0] returns True and [5] returns False. Why is the current total checked before it is added to the set?





Show a worked solution

For [0], current_total becomes 0; current_total - target is 0 and is already in {0}. That earlier zero represents the position before the element, so [0] is a nonempty match. For [5], the needed total 5 is absent from {0}, so the result is False. Adding 5 first would let it match itself and wrongly accept an empty range.



Using a set of values instead of prefix totals, or inserting the current total before checking it.



Review bracket matching as a reader

A valid bracket string closes each opening bracket with the same type, in the correct nesting order.

This bracket-matching example follows an A2SV student-code comparison. The input contains only (), [], and {} characters. A stack keeps the openings that still need a match; the most recent opening must close first. That is why counts alone cannot reject ([)].

Names such as closing_for and openings describe the two data structures. The short-circuit condition checks that the stack is nonempty before popping it. At the end, an empty stack means every opening was closed. The algorithm uses O(n) time and up to O(n) stack space.

Trace a mismatch, not just a successful input

Follow the invalid input ([)] one character at a time. First ( is stored as an unclosed round bracket. Next [ is stored above it as an unclosed square bracket. When ) arrives, the most recent opening is [, which needs ]. This is a mismatch, so the function returns False immediately.

Now follow ([]. The first two characters open a round and a square bracket. The last character ] matches the square opening, so that opening is removed. The round opening ( remains when the input ends. The final empty-stack check therefore returns False. In contrast, adding ) to form ([]) closes the last opening and returns True.

def brackets_match(text):
    closing_for = {"(": ")", "[": "]", "{": "}"}
    openings = []
    for char in text:
        if char in closing_for:
            openings.append(char)
        elif not openings or closing_for[openings.pop()] != char:
            return False
    return not openings

assert brackets_match("([]){()}")
assert not brackets_match(")")
assert not brackets_match("([)]")
assert not brackets_match("([]")

Try it yourself

Explain which check rejects each of these inputs: ), ([)], and ([].





Show a worked solution

The first is rejected because a closing bracket arrives with no opening. The second is a type mismatch against the latest opening. The third leaves an unmatched opening at the end. These are three different failure mechanisms and deserve separate tests.



Assuming equal numbers of opening and closing brackets imply correct nesting.



Name the reason a pointer moves

Choose two vertical lines that hold the most water. Their area is the distance between them multiplied by the shorter height.

Compare how the two versions communicate the same pointer decision. Follow one move with the supplied heights; check whether the names, stopping condition and comment let another reader explain that move. The full search is available for a deeper trace.

Replace li, l, and r with meaningful boundary names. Instead of looping over values you never use, write a while condition that says exactly when a container still has width. These changes expose the algorithm rather than merely making the code prettier.

Why move the shorter line? If you keep it and move the taller line inward, width decreases while the limiting height cannot increase. That cannot improve the current area. Discard the shorter boundary and look for a taller replacement. This argument explains the pointer move; a comment saying increment left would not.

Trace the decision with actual heights

Each array value is the height of one vertical line, and neighboring lines are one unit apart. In the example below, the first and last lines are 8 units apart and have heights 1 and 7. Water reaches only the shorter height, 1, so their area is 1 × 8 = 8. Moving the left endpoint to the next line gives height 8 on the left, height 7 on the right, and width 7.

With [1, 8, 6, 2, 5, 4, 8, 3, 7], the outer area is 1 × 8 = 8. Moving the left pointer gives 7 × 7 = 49. The full search keeps that maximum. Heights are non-negative integers; for fewer than two lines, this implementation returns 0. Each iteration moves a pointer inward, giving O(n) time and O(1) extra space.

# Before: the loop variable is unused and the stopping rule is buried.
def max_area_before(li):
    l, best, r = 0, 0, len(li) - 1
    for _ in li:
        best = max(best, min(li[l], li[r]) * (r - l))
        if li[r] < li[l]:
            r -= 1
        else:
            l += 1
        if l >= r:
            break
    return best

# After: the same supported results with explicit pointer names and loop bounds.
def max_water_area(heights):
    left, right = 0, len(heights) - 1
    best = 0
    while left < right:
        width = right - left
        height = min(heights[left], heights[right])
        best = max(best, width * height)
        # Keeping the shorter boundary cannot improve the area.
        if heights[left] <= heights[right]:
            left += 1
        else:
            right -= 1
    return best

assert max_water_area([1,8,6,2,5,4,8,3,7]) == 49
assert max_water_area([]) == 0
for heights in ([], [5], [1,8,6,2,5,4,8,3,7]):
    assert max_area_before(heights) == max_water_area(heights)

Try it yourself

At heights 8 and 7 separated by distance 7, which pointer should move, and why does keeping height 7 while shrinking the width not help?





Show a worked solution

Move the boundary with height 7. Keeping it limits the height to at most 7 while the width gets smaller, so the area cannot exceed the current 49. If both heights are equal, either side can be moved without losing a better pair that uses the discarded boundary.



Explaining pointer movement as a trick to memorize instead of showing which candidates it safely eliminates.



Name the node examined by each recursive call

To validate a binary search tree, each node must fit the bounds inherited from all of its ancestors.

Judge the parameter names by the information each call needs: the current node and its permitted bounds. Follow the path to node 6 in the supplied tree before tracing every recursive call. That path is enough to explain the exercise’s naming and bound decisions.

A node is one value in a tree, with links to up to two child nodes: left and right. The root is the top node. A subtree contains a node and everything below it. Ancestors are the nodes passed on the path from the root down to the current node; a bound may come from any of them, not only the immediate parent.

A binary search tree here has strictly smaller values on the left and strictly larger values on the right; duplicates are not allowed. Checking only a node against its immediate children misses deeper violations. Pass the permitted lower and upper bounds down the recursion.

Recursion calls the same function on a smaller part of a structure; here each call handles a subtree. Consider current rather than root as the node parameter inside a recursive helper. Both names can work, but current makes it clearer that each call is examining a different node. The important improvement is understanding each parameter: the left subtree inherits a tighter upper bound, and the right subtree a tighter lower bound.

A violation that a parent-only check misses

In a tree rooted at 10, suppose its right child is 15 and that child’s left child is 6. Although 6 is less than 15, it is inside 10’s right subtree and must also be greater than 10. The inherited bound catches it. The code represents a node as (value, left, right), with None for an empty subtree.

def valid_bst(current, lower=float("-inf"), upper=float("inf")):
    if current is None:
        return True
    value, left, right = current
    if not lower < value < upper:
        return False
    return (
        valid_bst(left, lower, value)
        and valid_bst(right, value, upper)
    )

assert valid_bst((10, (5, None, None), (15, None, None)))
assert not valid_bst((10, None, (15, (6, None, None), None)))

Try it yourself

For the node 6 in this tree, what are lower and upper, and which condition fails?





Show a worked solution

The bounds are 10 and 15. The check 10 < 6 < 15 fails. An empty subtree is valid; a nonempty node must satisfy strict bounds. The algorithm visits at most n nodes and uses O(h) call-stack space for tree height h.



Renaming root to current while still checking only the immediate parent.



Make changing dependencies explicit

A function is easier to reason about when its result depends on visible inputs rather than changing module-level state.

Hidden mutable state makes code harder to reason about: if a function reads a divisor that another function changes, identical arguments may produce different results depending on call order. Pass the divisor explicitly when it is part of the calculation.

In this example, assigning value inside set_value creates a local name because no global or nonlocal declaration redirects it. It does not update the caller’s integer. Return the new value and assign it at the call site if an update is intended. Module-level constants are different from changing shared state: they can make a fixed rule clearer.

Visible inputs, visible result

Here divide receives both operands and rejects a zero divisor. No setup function has to run first. The second example shows why assigning value = 5 inside a function does not change the caller’s integer.

def divide(value, divisor):
    if divisor == 0:
        raise ValueError("divisor must not be zero")
    return value / divisor

def set_value(value):
    value = 5

number = 1
set_value(number)
assert number == 1
assert divide(12, 3) == 4

Try it yourself

number starts at 1. The shown set_value(number) assigns value = 5 inside the function and returns nothing. What is number afterward? Show how returning a value and assigning it at the call site would make number become 5.





Show a worked solution

number remains 1: value is a local parameter, and assigning it does not reassign the caller’s name. One explicit replacement is def set_value(value): return 5, followed by number = set_value(number). The caller now assigns the returned 5 to number. No global variable or shared mutation is needed.



Repeating “never use globals” without distinguishing constants, local rebinding, and shared mutable state.



Keep small style choices consistent

Consistent imports, spaces, and names let a reader focus on the logic instead of repeatedly adjusting to the writer’s style.

Use separate imports and readable operators. In Python, import os and import sys go on separate lines; related names from the same module can share a from import. Remove unused imports rather than filling a file with standard boilerplate.

Choose a project convention and automate mechanical formatting where possible. A formatter can standardize spaces and line breaks, but it cannot tell whether a variable describes the right concept or whether a condition is correct. Avoid reformatting unrelated files in a behavior-change pull request; it hides the important lines.

Make the expression easy to scan

Consider this difference-of-squares calculation. Spacing exposes the two grouped terms; the name tells the reader what the expression represents. The assertion checks the value, not whether a human likes the formatting.

def difference_of_squares(first, second):
    return (first + second) * (first - second)

assert difference_of_squares(5, 2) == 21

Try it yourself

A pull request fixes one boundary check but reformats 40 unrelated files. What would you ask the author to do, and why?





Show a worked solution

Ask for the unrelated formatting to be separated into its own change. A focused diff makes the behavior change easier to inspect and revert. If formatting is required in the edited file, explain the scope rather than demanding zero whitespace changes everywhere.



Using a review discussion to enforce a personal style already handled by the project’s formatter.



Use these habits when an interview gets difficult

Under time pressure, clear names and small steps reduce the work you must hold in your head.

You may need to explain, implement, and debug at the same time. A named helper lets you finish one piece of reasoning and then use it as a building block. State the helper’s inputs and result before writing it; explain a completed block rather than narrating every keystroke.

If you cannot finish an optimal algorithm immediately, explain a correct simpler approach and its cost, then look for the bottleneck. Do not conceal uncertainty with dense code or a memorized trick. The interview examples in this lesson are practice in making your reasoning inspectable, not a replacement for understanding the problem.

A concrete explanation during implementation

For the hourglass search: I will first write a helper that adds the seven cells for one top-left position. Then I will enumerate all valid positions and keep the largest candidate. I will test an all-negative grid because zero is not a safe initial maximum. That is a plan another person can follow.



Try it yourself

You implemented the bracket loop but have not tested it. Give a short update to the interviewer, then name two bracket-only test inputs with their expected results and reasons.





Show a worked solution

“The loop now tracks unmatched openings; I have not tested it yet. Next I will try ([)], expecting False because ) does not match the latest opening [. I will also try ([], expecting False because the outer ( remains open at the end.” These are planned checks, not reported passes.



Claiming that tests passed when you have only listed the inputs you would like to try.



Refactor without quietly changing the rule

Refactoring improves code structure while preserving the behavior callers rely on. A new discount policy is a separate behavior change.

The same habits matter when you change code with a team. Share logic when callers must follow the same rule. Similar-looking lines are not enough: a historical invoice may preserve an old price while a live cart uses today’s price.

Before extracting a helper, record representative results and boundaries. Then make the structural change and rerun those checks. If the existing behavior is wrong, identify that separately: a test that preserves a bug is useful evidence of the current behavior, not a reason to keep it forever.

Extract one pricing rule

The exercise policy is a 10% reduction for books and no reduction for other item types. calculate_item_price names that rule; calculate_cart_total combines item results. Valid items have type and a non-negative numeric price. This example does not introduce tax, currency rounding, or missing-field policies.

BOOK_DISCOUNT_RATE = 0.10

def calculate_item_price(item):
    if item["type"] == "book":
        return item["price"] * (1 - BOOK_DISCOUNT_RATE)
    return item["price"]

def calculate_cart_total(items):
    return sum(calculate_item_price(item) for item in items)

assert calculate_item_price({"type": "book", "price": 100}) == 90
assert calculate_cart_total([]) == 0

Try it yourself

You extract the book discount into a helper and change it from 10% to 15% in the same commit. Is that only a refactor?





Show a worked solution

No. The extraction changes structure; the new rate changes results. For a book priced at 100, the result moves from 90 to 85. Explain and test the policy change separately so reviewers can judge both decisions.



Centralizing two different policies just because they currently contain the same multiplication.



Separate the calculation from the outside world

An email operation and a calculation have different failure modes. Give each a boundary you can test.

A side effect changes something outside a calculation: sending mail, writing a file, or recording a payment. If an arithmetic function also sends mail, testing arithmetic now depends on delivery. Pass the sending function into a function that first calculates the total and then sends it; a test can substitute a function that appends to a list.

Error behavior is part of the function’s contract. Here negative quantity is invalid, so calculate_total raises ValueError before any send. Returning None can be appropriate for a documented not-found result; hiding every failure behind None is not. The caller must know which outcomes it has to handle.

Verify that invalid input sends nothing

receipts.append is a stand-in for delivery and records values in memory. It does not send messages. A failing validation must stop execution before this side effect. An actual delivery service could fail separately, so this small test does not prove reliable email delivery.

def calculate_total(price, quantity):
    if quantity < 0:
        raise ValueError("quantity must not be negative")
    return price * quantity

def complete_order(price, quantity, send_receipt):
    total = calculate_total(price, quantity)
    send_receipt(total)
    return total

receipts = []
assert complete_order(12, 3, receipts.append) == 36
try:
    complete_order(12, -1, receipts.append)
except ValueError:
    pass
else:
    raise AssertionError("negative quantity accepted")
assert receipts == [36]

Try it yourself

What does the final assertion prove, and what does it leave untested?





Show a worked solution

It proves the rejected negative-quantity attempt added no receipt to the local recorder. It does not prove a real email arrives, survives retries, or is sent exactly once after a network failure. Those are separate integration and delivery requirements.



Using one happy-path arithmetic test as evidence that a real external service works.



Give each change a reviewable history

Git records snapshots. A branch keeps one line of work separate while you develop and review it.

A Git working directory contains your current files. The staging area holds the exact file versions selected for the next commit: git add selects them and git diff --staged shows the selection. A local commit records that selection. If you edit a staged file again, add it again to include the newer version.

A typical team flow is base branch → working branch → focused commit → publish branch → pull request → review → revise and recheck → merge. Agree the team’s rules before publishing or merging. The exercise below stops at local commits; a commit does not prove tests passed or deploy anything.

Inspect before recording

Workshop route: git-practice/ is the optional local Git exercise; demo/ is the cart you will set up, test and review; examples/test_item_price.py is the standalone assertion example; homework/ is your independent review. Start the homework with CURRENT-ASSIGNMENT-en.txt at the archive root. Keep demo and homework discount rules separate. The file links at each example open the relevant material.

Download and extract the workshop, then open a terminal at its root. git-practice is a separate supplied folder containing cart.py, check_cart.py, and .gitignore; it is not the site repository or the original demo. Check git --version first. Replace Your Name and you@example.com with your own commit identity; these settings apply only to this practice repository. The first commands record the supplied starting files.

After creating the branch, rename calc to calculate_item_price in cart.py and update its import and both calls in check_cart.py. Keep the discount behavior unchanged. Then run the second command block below to check and record that rename. On Windows use py check_cart.py instead of python3 check_cart.py. The expected check result is exit status zero with no assertion failure.

cd git-practice
git init
git config user.name "Your Name"
git config user.email "you@example.com"
git add cart.py check_cart.py .gitignore
git diff --staged
git commit -m "chore: record cart practice baseline"
git switch -c refactor/cart-function-name


Try it yourself

You changed a boundary check and an unrelated logo. Should they usually share a commit? What does committing say about test results?



python3 check_cart.py
git diff
git add cart.py check_cart.py
git diff --staged
git commit -m "refactor: name cart calculation clearly"

Show a worked solution

Usually separate them because they solve different problems and may need independent review or reversal. A commit says a snapshot was recorded, not that tests passed. Report the checks you actually ran and their results separately.



Treating a recorded commit, a pushed branch, and a deployed release as the same event.



A pull request should explain the decision

A pull request proposes a change for review. Its description connects the diff to the problem it solves.

Write what changed, why the old behavior was a problem, and how you checked the new behavior. A reviewer should not have to reconstruct the requirement from variable names. Include important limits, especially when a change might look broader than it is.

The description must distinguish planned validation from completed validation. If you have not run a command, say so. Screenshots can support a visual change, but they cannot establish arithmetic or backend behavior on their own. Keep unrelated cleanup outside the diff when it would distract from the decision.

A concrete review description

For this hypothetical quantity change, the old multiplication returned negative totals. The proposed rule rejects negative quantities and preserves positive and zero quantities. The description below deliberately leaves validation unclaimed; replace it with actual results after running the checks.

Problem: Negative quantity currently produces a negative total.
Change: Raise ValueError for quantity < 0; preserve zero and positive results.
Scope: No currency or rounding changes.
Validation: Not run yet. Check positive, zero, and negative quantity.

Try it yourself

For the quantity change above, rewrite “Fixed stuff; should work” as a two- or three-sentence pull-request description. The old code returned negative totals; the new rule raises ValueError for negative quantities. Positive/zero results and rounding stay unchanged, and no tests have been run yet.





Show a worked solution

Negative quantities previously produced negative order totals. This change raises ValueError for quantity < 0 while preserving positive and zero results and the existing pricing/rounding rules. Validation has not been run yet; the planned checks cover positive, zero and negative quantities.



Filling a test section with commands you intended to run rather than observed results.



Make the repository usable by someone new

A README should let a new contributor get from a fresh checkout to a running program and meaningful checks.

Explain what the project does, its prerequisites, installation, how to run it, and how to test it. State required configuration with placeholder values. Keep secrets out of examples, version control, and screenshots. A folder structure is helpful only when it explains where real responsibilities live.

Try the documented steps in a clean environment. A command that works only because your machine already has an undeclared dependency is incomplete documentation. Do not claim a repository is ready just because it has files named README.md and requirements.txt.

Run the cart workshop

Continue with demo/, the workshop’s cart project. If you tried git-practice/, return to the extracted archive root first; cd demo below starts there. The commands create an isolated environment and run the existing weak test, which later sections strengthen. On Windows, use py -m venv .venv and .venv\Scripts\python in place of the POSIX Python paths below.

cd demo
python3 -m venv .venv
.venv/bin/python -m pip install -r requirements.txt
.venv/bin/python -m pytest -q

Try it yourself

A teammate installed pytest in demo/.venv, but from demo runs python3 -m pytest -q using the system interpreter and sees “No module named pytest.” What command would you try next, and why?





Show a worked solution

From demo, run .venv/bin/python -m pytest -q; on Windows use .venv\Scripts\python -m pytest -q. This selects the environment where pytest was installed instead of the system interpreter. If pytest is still missing there, install requirements.txt with that same environment’s Python and retry; a global install is unnecessary.



Listing commands without saying which folder or Python environment they apply to.



A test needs a result that can be wrong

A useful test checks a specific promise. “The total is positive” is too weak to verify a discount.

The workshop demo test only asserts that the result is greater than zero. It would accept many wrong totals. For a book priced at 100 with a 10% discount, the expected item price is 90; assert that result so a missing or incorrect discount becomes visible.

pytest discovers functions named test_ in test files and reports failed assertions. Use names that describe the behavior. For calculations using floating-point values, pytest.approx compares with a tolerance; choose tolerances appropriate to the domain. These teaching calculations use floats and do not specify a production money representation.

Test the discounted and undiscounted paths

Continue from the demo folder after the previous setup. The archive already includes this standalone example in ../examples/test_item_price.py. Run .venv/bin/python -m pytest -q ../examples/test_item_price.py; on Windows run .venv\Scripts\python -m pytest -q ../examples/test_item_price.py. If you type the example yourself, save it as demo/test_item_price.py and run .venv/bin/python -m pytest -q test_item_price.py from demo.

The calculation is included so this example stands alone. To test the workshop implementation itself, import calculate_item_price from src.cart_improved rather than copying it into a new test.

import pytest

def calculate_item_price(item):
    if item["type"] == "book":
        return item["price"] * 0.90
    return item["price"]

def test_book_gets_ten_percent_discount():
    assert calculate_item_price({"type": "book", "price": 100}) == pytest.approx(90)

def test_other_item_keeps_its_price():
    assert calculate_item_price({"type": "other", "price": 100}) == pytest.approx(100)

Try it yourself

If the book multiplier accidentally changes from 0.90 to 0.95, which assertion catches it? Would total > 0 catch it?





Show a worked solution

The expected result of approximately 90 catches a result of 95. The positive-total check accepts both and therefore misses the wrong rate. The other-item test checks that the book rule is not applied to every item.



Writing a test whose expected result is calculated by calling the same function being tested.



Choose tests for a reason, not a percentage

Coverage reports which code ran. It does not tell you that the test checked the right outcome.

A test can execute every line and still miss a defect if its assertion is weak. Use coverage to find unvisited code, then ask which important outcomes remain unchecked. A universal target such as 80% does not tell you whether your discount rule or invalid-input handling is adequately tested.

Choose cases from the contract and the likely mistakes. For the bracket checker: valid nesting, mismatched types, an early closing bracket, and leftover openings. For the cart: empty input, book and non-book prices, discount flags, and premium status. Do not invent behavior for unsupported input types without first defining the requirement.

Connect each case to a failure

The demo applies a book reduction, an optional general reduction, and an optional premium reduction. Test each alone and at least one combination: a helper may be omitted, use the wrong rate, or run for the wrong user. In this calculation the 0.90 and 0.95 factors commute; merely reversing those multiplications does not create a different mathematical result.



Try it yourself

The demo gives books 10% off, then optionally takes 10% off the subtotal and 5% off for premium users. You see 100% line coverage but only total > 0. Is that enough? Propose two stronger checks, giving each input/flags and expected total; prose assertions are fine.





Show a worked solution

No: a wrong positive amount still passes. Check 1: one book priced 100, no general discount and no premium status, should total 90. Check 2: the same book with the general discount enabled and a premium user should total 76.95: 100 × 0.90 × 0.90 × 0.95. Compare float results with a suitable tolerance. The first can catch a missing book discount; the second can catch a missing or wrong extra reduction.



Treating a coverage percentage as proof of correctness or requiring meaningless tests just to reach a target.



Automate the checks, then enforce the result

Continuous integration runs repeatable checks on changes. Repository rules decide whether a failing check blocks a merge.

A team can run its tests, formatter, linter, and build automatically on each pull request. Start with checks that provide useful feedback for this project. A formatter checks layout; a linter looks for defined patterns of suspicious code; neither replaces tests of the application’s behavior.

A CI workflow by itself does not guarantee that failing code cannot merge. Configure required checks and the appropriate branch protections or rulesets. Consider who can bypass those rules. A green check only means the configured checks passed; an untested requirement can still be wrong.

Make the local command reproducible in CI

For the cart workshop, run the same pytest command locally and in a clean CI environment with the documented dependencies installed. If it fails, preserve the failure output and fix the cause. Silencing a failure or making the test always succeed removes the protection.



Try it yourself

The CI test fails, but the merge button is still enabled. Name the two separate things you would investigate.





Show a worked solution

First investigate the failing test: reproduce it and determine whether the code, test, or environment is wrong. Separately inspect repository rules to see whether that check is required and whether the current actor can bypass it. Fixing enforcement does not fix the underlying test failure.



Saying CI prevents every bad merge without checking which statuses are actually required.



A review comment needs evidence and impact

Find a concrete failure, show how it happens, and give the author a useful next step.

Start with the requirement and the changed behavior. Read the surrounding callers, not only the modified function. Review correctness, readability, error handling, tests, and scope. Prioritize a reproducible bug over a preference about whether you would have written the code differently.

A useful comment connects an observation to its consequence: find_email returns None when a user is missing, but normalized_email immediately calls lower. A missing user therefore raises AttributeError. Suggest handling the not-found outcome, and ask for a test of that path. Do not demand exceptions in every lookup; decide which outcome the interface should promise.

Follow the result into its caller

This intentionally faulty example includes the caller so the failure is visible. The lookup’s None is not automatically wrong; the unhandled combination is the problem. A test with an existing user alone will never reveal it.

def find_email(users, user_id):
    return users.get(user_id)

def normalized_email(users, user_id):
    return find_email(users, user_id).lower()

assert normalized_email({1: "A@EXAMPLE.COM"}, 1) == "a@example.com"
# Intentionally faulty: normalized_email({}, 1) raises AttributeError.

Try it yourself

For normalized_email({}, 1), write a review comment identifying the failure and its effect on the caller. Propose one concrete next step to resolve or expose it.





Show a worked solution

“With users={} and user_id=1, find_email returns None. normalized_email then calls .lower() on None and raises AttributeError, so a missing user crashes this path. Could we define the missing-user outcome and handle it before .lower(), for example returning a documented None?” A test that reproduces this missing-user call is another useful next step.



Writing “bad error handling” without a failing input, an impact, or an actionable suggestion.



Keep the review about the code

A review is a conversation about a change, not a contest between its author and its reviewer.

Separate blocking defects from suggestions. A reproducible crash on supported input needs resolution. A personal name preference may be optional. State the reason and the severity so the author can prioritize. Questions can invite discussion, but a direct explanation of a known bug is also appropriate.

As the author, understand the concern before defending your implementation. Fix it, explain why the current approach meets the requirement, or ask for clarification. After changing the code, say what changed and what you verified. If you disagree, compare tradeoffs and evidence; an approval is not a prize for winning an argument.

A useful exchange

Reviewer: Blocking: missing user raises AttributeError in normalized_email; please handle that supported case and test it. Author: Agreed. I now return None for a missing user and added a test for that path. I ran the lookup tests; they passed. That last sentence belongs only after an actual run.



Try it yourself

A reviewer asks you to rename current to root because they prefer it. How would you respond if current accurately describes a recursive parameter?





Show a worked solution

“I used current because this parameter is the node examined by each recursive call, not always the original tree root. Is there a team convention or a specific ambiguity that makes root preferable here? I’m happy to follow an established convention; otherwise I suggest keeping current to describe those changing calls.”



Blocking a correct change on personal style, or dismissing a real bug as a style preference.



Use AI to challenge a solution you understand

AI can suggest tests or review findings. You still decide which suggestions match the actual requirement and verify the resulting code.

Provide the function, its callers when relevant, the supported inputs, and the behavior to preserve. Ask for a focused result: counterexamples, missing tests, or a small refactor. A vague request to improve everything encourages unrelated changes and makes the answer harder to check.

Read generated assertions as carefully as generated implementation. A model may invent a policy, repeat the same weak assertion, or confidently explain code it has not run. Do not send secrets or unnecessary personal data in the prompt. Treat AI review as another source of hypotheses; it does not replace testing or human responsibility for the change.

A prompt tied to a real boundary

For the hourglass helper, explicitly allow negative cell values and say that the grid is rectangular and at least 3 by 3. That context lets you judge whether a suggested zero initialization or empty-grid policy belongs to the problem. Ask the model to label reasoning separately from actual execution.

You can use the prompt below directly. Keep the input contract visible so the reviewer does not invent unsupported requirements.

Review max_hourglass_sum for this contract:
- Rectangular integer grid, at least 3 rows and 3 columns.
- Negative values are allowed.
- Return the largest SINGLE seven-cell hourglass sum.
Give a counterexample for each correctness finding.
Suggest focused tests; distinguish hand reasoning from executed results.
Do not redesign the input contract.

Try it yourself

AI proposes max(0, candidate) as the first maximum for an all-negative grid. How would you check and respond?





Show a worked solution

“For a 3 by 3 grid filled with -1, the only hourglass contains seven -1 values and sums to -7. max(0, -7) is 0, so the proposed initialization returns an amount that no hourglass has. Initialize from the first valid candidate instead. I traced this counterexample by hand; I have not run the code.”



Accepting a polished explanation as evidence that generated code was executed or meets the requirement.



Workshop: review the cart code

Apply the habits together: inspect the cart implementation, calculate the expected amount, and write useful review comments.

Download the workshop and open demo/src/cart.py. The calc function takes items, user, and a flag named d. It applies the book discount, the optional general discount, and then a premium discount. process_cart also prints a message. Compare this with cart_improved.py, but write your observations before reading the reference.

Preserve the stated discount policy while improving structure. Better names and extracted helpers are structural changes. New input validation or a different rounding rule needs its own requirement and tests. The original reference is useful for comparison, not a complete production checkout system.

Compute the expected result before reviewing the test

For one book at 100 and another item at 50, the book rule gives 90 + 50 = 140. With the general discount enabled, 140 × 0.90 = 126. With a premium user as well, 126 × 0.95 = 119.70. The existing > 0 assertion cannot distinguish that from many wrong totals.

Write one correctness/test comment and one readability/design comment. Then run the original tests, strengthen the expected-result assertion, and verify the implementation against your independently calculated result.

Book: 100 × 0.90 = 90
Other item: 50
Subtotal: 140
General discount: 140 × 0.90 = 126
Premium discount: 126 × 0.95 = 119.70

Try it yourself

The existing demo/tests/test_cart.py test uses one book priced 100, a premium user and general discount=True, but asserts only calc(...) > 0. Write one test/assertion review comment and one naming/responsibility comment for the demo. Which can catch a wrong premium rate?





Show a worked solution

Test comment: “In demo/tests/test_cart.py, test_calc accepts any positive result for this premium order. Expect approximately 76.95 for its existing one-book fixture: 100 × 0.90 × 0.90 × 0.95. That assertion can catch a wrong premium rate; > 0 cannot.”

Naming comment: “In demo/src/cart.py, calc’s flag d does not explain its purpose. Rename it discount_enabled and update its uses so callers can see that it controls the general discount.” This improves readability; the rename itself does not verify the premium calculation.



Saying the original weak test proves the reference implementation or your refactor is fully correct.



Finish with a review someone can act on

Use the homework folder to write, verify, and explain your own review. The goal is useful observations, not a quota of superficial comments.

Open homework/src/orders.py and its tests. Books receive 10% off and VIP adds 5% off; unlike the demo, there is no optional general discount. A book at 100 should cost 90 without VIP and 85.50 with VIP. The archive preserves the old ASSIGNMENT.md for reference; its numerical comment quotas do not govern this version. Follow CURRENT-ASSIGNMENT-en.txt at the archive root instead.

Record the file and location, the observed issue, why it matters, and a concrete suggestion. Include at least one independently calculated test expectation, one naming or responsibility improvement, and one setup/documentation observation you actually checked. Distinguish bugs from optional improvements, and explain uncertainty instead of presenting it as a fact.

Before finishing, run the relevant checks and inspect the final diff. State what you ran, what passed or failed, and what remains unverified. The lesson’s habit is simple to practice: make your reasoning visible, make the important behavior checkable, and make the next person’s work easier.

A deliverable that shows your reasoning

Submit your review notes, a focused patch if you made one, and observed test results. The existing assertion is calc(items, False) > 0: it checks a non-VIP purchase without requiring its correct amount of 90. It never calls VIP=True. A strong review therefore requests an expected-90 non-VIP check and a separate expected-85.50 VIP check, rather than claiming the existing test exercised VIP.



Try it yourself

Draft one final review finding for the homework. Include a location, evidence, impact, and proposed check. If you have not run it, say so.





Show a worked solution

“In homework/tests/test_orders.py, test_calc calls calc(items, False) for a book priced 100 but asserts only > 0. It would accept incorrect positive amounts, and it never exercises VIP=True. Expect approximately 90 for the existing non-VIP call and add a separate VIP=True check expecting 85.50. These are proposed checks; I have not run them.”



Copying the demo’s extra general discount into the homework, or claiming unexecuted checks passed.