Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • sum first n numbers using for
  • verify result using formula n(n+1)/2
  • write variants (even/odd sums)

Basic solution

n = int(input())
total = 0
for i in range(1, n + 1):
    total += i
print(total)

Dry run for n = 4

  • total = 0
  • add 1 -> 1
  • add 2 -> 3
  • add 3 -> 6
  • add 4 -> 10

Formula cross-check

sum = n * (n + 1) // 2 Use formula for quick verification in exam output questions.

Variant 1: sum of even numbers up to n

n = int(input())
total = 0
for i in range(2, n + 1, 2):
    total += i
print(total)

Variant 2: sum of odd numbers up to n

n = int(input())
total = 0
for i in range(1, n + 1, 2):
    total += i
print(total)

Exam hints and traps

  • inclusive range needs n + 1
  • range(n) starts from 0, not 1
  • for large n, formula is faster than loop

Practice

  1. Write loop sum for first n natural numbers.
  2. Modify to sum from a to b inclusive.
  3. Predict output for n=0.

Answers

total = 0
for i in range(a, b + 1):
    total += i
  1. 0