Sum of Evens
Easy · 30 XPPrint the sum of all even numbers from 1 to 100 inclusive.
2550
sum(range(2, 101, 2)), or a loop with i % 2 == 0.
print(sum(range(2, 101, 2)))
Run your code to check it…
How to approach Sum of Evens
Two questions decide this problem: which numbers count, and where the range stops. The even numbers from 1 to 100 are 2, 4, 6 and so on up to 100, so you want a sequence that starts at 2, steps by 2 and includes 100.
range(start, stop, step) generates exactly that, as long as you remember that stop is excluded: to include 100 the stop has to be 101. Hand the range to sum() and you are done in one line. A loop that checks i % 2 == 0 gets the same answer and is worth writing once, because the modulo test is how you filter when the values are not a neat arithmetic sequence.
Worked through on this data
- The evens are 2 × 1, 2 × 2, … 2 × 50, so the sum is 2 × (1 + 2 + … + 50).
- 1 + 2 + … + 50 is 50 × 51 / 2 = 1275 (Gauss's pairing trick: 1 + 50, 2 + 49, … gives 25 pairs of 51).
- 2 × 1275 = 2550, which is the target output. Use this to sanity-check whatever your code prints.
Common mistakes
range(2, 100, 2)stops at 98 and prints 2450: the stop value is never included.- Testing
i % 2 == 1sums the odd numbers instead (2500). - Printing inside the loop prints a running total on every line, not one number.
Time and space
The range or loop touches 50 numbers, so it is O(n) in the size of the range. The closed-form formula is O(1): it costs the same for 1 to 100 as for 1 to a billion.
Where this shows up
Filtering and then aggregating is the shape of most reporting code: total the paid invoices, count the failed jobs, average the weekend orders. The filter changes; the pattern does not.
Take it further
Write sum_multiples(limit, k) that sums every multiple of k up to and including limit, then sum the multiples of 3 or 5 below 1000 without counting 15, 30, 45 twice.