Zed-King Institute

    Python Program to Find the Sum of Even Numbers from 1 to N

    easyfor loopPython

    A loop with an accumulator — a variable that collects a running total.

    The question

    Read an integer n and print the sum of all even numbers from 1 to n (both included).

    The code

    program.py

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

    Input

    46

    Output

    Sum = 552

    How it works

    1. 1Start total at 0.
    2. 2range(2, n + 1, 2) gives only even numbers: 2, 4, 6 … up to n.
    3. 3Add each one to total, then print the total after the loop.

    Common mistakes

    • Writing range(2, n, 2) — if n is even, n itself is left out.
    • Putting print inside the loop, which prints every partial total.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in for loop