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.
1# Take n as input2n = int(input("Enter n: "))34# Calculate sum of even numbers5sum_even = 06for i in range(2, n + 1, 2):7 sum_even += i89print(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
Initialize sum_even to zero.
- 2
Visit evens from two through n.
- 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.
๐Related Content
- ๐
Phase 2 - Learn Concepts
Review Phase 2 concepts and explanations
- ๐
Phase 2 - Quiz
Test your Phase 2 understanding with quiz questions
- ๐ป
Phase 2 - All Practice Problems
Explore all practice problems for Phase 2
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum