Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Sum of All Even Numbers Up to N

Sum even integers no greater than an entered limit in Python. Beginners trace a stepped range, a zero accumulator, and limits that may be odd or below two.

BeginnerPhase 2 - Level 1: Basic LoopingExample 8 of 14
sum-of-all-even-numbers-up-to-n.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Calculate sum of even numbers
5sum_even = 0
6for i in range(2, n + 1, 2):
7 sum_even += i
8
9print(f"Sum of even numbers up to {n}: {sum_even}")

Output

Enter n: 10
Sum of even numbers up to 10: 30

In this one

  • Accumulate selected terms
  • Use an even-stepped range
  • Handle odd upper bounds

How it works

  1. 1

    Initialize sum_even to zero.

  2. 2

    Visit evens from two through n.

  3. 3

    Add each visited value and print the final sum.

Edge cases

What if n is one?

What if n is one?

No values are visited, leaving zero.

Is n included when it is even?

Is n included when it is even?

Yes. The excluded stop is one larger than n.

What's going on

sum_even begins at zero. The range starts at two and advances by two, so only even integers are added.

The stop n + 1 allows an even n to be included. With n equal to seven, the visited values are two, four, and six, totaling twelve. An odd limit does not need special handling because the step simply never lands on it.

What if n is one? No values are visited, leaving zero.

Is n included when it is even? Yes. The excluded stop is one larger than n.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What is summed for n = 5?

Pick an answer to check it.

Question 2

What if n is one?

Pick an answer to check it.

Questions people ask

What if n is one?

No values are visited, leaving zero.

Is n included when it is even?

Yes. The excluded stop is one larger than n.

What is summed for n = 5?

2 and 4.