Loops · Python example
Add the first n natural numbers with a loop and compare the closed formula.
Adding the numbers from 1 to n can be done iteratively or with a closed formula. This example computes both and shows that they agree.
n = 100
loop_total = 0
for value in range(1, n + 1):
loop_total += value
formula_total = n * (n + 1) // 2
print(f"Loop result: {loop_total}")
print(f"Formula result: {formula_total}")