""" write a loop that adds up the numbers from 1 to n """ def loop_invariant(i, total): # the sum so far is i*(i+1)/2 which is 1+2+3+...i # for each i as we loop from 1 to n total_should_be = i * (i+1) // 2 if total != total_should_be: print("OOPS : loop invariant failed ") n = 10 total = 0 for i in range(1, 1+n): total = total + i loop_invariant(i, total) # check to see that our partial result is OK print("total of 1+2+...+10 is ", total)