Free lab Real Python 3. Zero installs. Your code stays in this browser. Open the playground

Sum of Evens

Easy · 30 XP

Print the sum of all even numbers from 1 to 100 inclusive.

Target output
2550
Blank · autosaved
PYsum-of-evens.py
Run your code to check it…
Guide

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

  1. The evens are 2 × 1, 2 × 2, … 2 × 50, so the sum is 2 × (1 + 2 + … + 50).
  2. 1 + 2 + … + 50 is 50 × 51 / 2 = 1275 (Gauss's pairing trick: 1 + 50, 2 + 49, … gives 25 pairs of 51).
  3. 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 == 1 sums 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.

Your next ten minutes

Write Python that does something useful.

Start free. No install, no card, no passive video marathon.

Start learning free → Explore the path