Sum of All Odd Numbers Up to N
Add odd integers from one up to a supplied limit with Python. Students trace a two-step range and compare an accumulated total with printing individual numbers.
1# Take n as input2n = int(input("Enter n: "))34# Calculate sum of odd numbers5sum_odd = 06for i in range(1, n + 1, 2):7 sum_odd += i89print(f"Sum of odd numbers up to {n}: {sum_odd}")
Output
Enter n: 10 Sum of odd numbers up to 10: 25
In this one
- Sum odd terms
- Include odd endpoints
- Separate listing from totaling
How it works
- 1
Initialize sum_odd to zero.
- 2
Visit one through n in steps of two.
- 3
Add those values, then print only the total.
Edge cases
What happens for n = 0?
What happens for n = 0?
The range is empty and the sum remains zero.
Is six added for n = 6?
Is six added for n = 6?
No. Only odd terms are visited.
What's going on
This loop selects odd values by starting at one and stepping by two. sum_odd keeps the combined total as each selected value arrives.
For n equal to six, the terms are one, three, and five, giving nine. Only the total is printed after the loop, unlike an exercise that lists every odd number. n + 1 makes an odd endpoint eligible for inclusion.
What happens for n = 0? The range is empty and the sum remains zero.
Is six added for n = 6? No. Only odd terms are visited.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
What is the total for n = 3?
Pick an answer to check it.
Question 2
What happens for n = 0?
Pick an answer to check it.
Questions people ask
What happens for n = 0?
The range is empty and the sum remains zero.
Is six added for n = 6?
No. Only odd terms are visited.
What is the total for n = 3?
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