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

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.

BeginnerPhase 2 - Level 1: Basic LoopingExample 9 of 14
sum-of-all-odd-numbers-up-to-n.py
1# Take n as input
2n = int(input("Enter n: "))
3
4# Calculate sum of odd numbers
5sum_odd = 0
6for i in range(1, n + 1, 2):
7 sum_odd += i
8
9print(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. 1

    Initialize sum_odd to zero.

  2. 2

    Visit one through n in steps of two.

  3. 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.