CodeRigor

FREE LESSON

Functions, control flow & contracts

Explicit returns, loops, keyword-only arguments and boundary validation for small dependable functions.

def creates a function. Arguments are object references bound to local names; a function can mutate a list argument, but assigning a new local name does not rebind the caller's variable. Return explicitly; reaching the end returns None.

The equality boundary is part of the function contract, not a minor numerical detail.

Inclusive threshold
start / 2
At threshold 0.5, scores at indices 1 and 2 are accepted, including the tie at exactly 0.5.
Inclusive threshold
At threshold 0.5, scores at indices 1 and 2 are accepted, including the tie at exactly 0.5.
Python
def clipped(x, *, low=0, high=1):
    if low > high:
        raise ValueError("inverted bounds")
    return min(high, max(low, x))


print(clipped(3, high=2))

* makes later parameters keyword-only, useful when two numeric settings can easily be swapped. Python uses and, or, not; chained comparisons such as 0 <= score <= 1 express intervals. Use if/elif/else for exclusive branches. range(n) supplies 0 through n-1, never n.

Python
total = 0
for i, score in enumerate([0.1, 0.8, 0.6]):
    if score < 0.5:
        continue
    total += i
print(total)  # 3

A contract answers edge cases before implementation. For a threshold use greater-than-or-equal if equality is accepted; an accidental > can fail exactly on a calibrated operating point. For batching, reject nonpositive sizes and include the final partial batch. Empty input should give no batches.

Batch starts use a half-open range; the remainder is still a valid batch.

Keep the final partial batch
Five records at size two produce lengths 2, 2 and 1. The last record is not discarded.
Keep the final partial batch
Five records at size two produce lengths 2, 2 and 1. The last record is not discarded.

Write a small loop first. Replace it with a comprehension only when the transformation stays readable. Exceptions communicate invalid requests; returning an empty result for an invalid batch size confuses invalid input with valid empty data. In the build, reason through five records at size two, then size one, then empty input. Each iteration must advance its start index.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Review parameters, return values, positional and keyword arguments. Apply those mechanics to the lesson’s keyword-only thresholds and finite batch validation; the build states its own edge-case contract.