State Input Contracts and Loop Invariants
Core idea
A precondition describes permitted input; a postcondition describes the required result. A loop invariant is a statement true before the loop and after each completed iteration. Prove initialization, preservation and the result at termination; also show progress toward termination.
def first(values): if not values: raise ValueError("empty input") return values[0]print(first([6, 9]))The contract rejects an empty list rather than returning an ambiguous result.
Trace an accumulator invariant
values = [4, -2, 5]total = 0for i, value in enumerate(values): total += value print(i + 1, total, total == sum(values[:i+1]))After k items, total equals the sum of the first k items. At k=0 it is zero; adding one value preserves the invariant. The slice is only a diagnostic here.
Common mistake
An invariant is not a termination proof by itself. A few tests are evidence, not proof for every input. Use explicit input checks instead of assertions for required validation.
Practice
Write an invariant for counting positive readings; trace an empty list and a list containing zero and negative values.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Contracts and invariants
Check your understanding of input contracts and invariants.
What is printed?
n=0for x in [0,2,-1,3]: n+=int(x>0)print(n)What is printed?
total=0for x in []: total+=xprint(total)When must a loop invariant hold?
What else is necessary for a termination argument?