Python Practice › Loop Programs › Program 18
Sum of odd numbers 1 to n
Write a Python program to find the sum of all odd numbers from 1 to n.
Input
n = 20
Output
Sum of odd numbers: 100
Approach
- Loop from 1 with a step of 2.
Solution
n = 20total = 0for i in range(1, n + 1, 2): total += iprint("Sum of odd numbers:", total)Output
Sum of odd numbers: 100
Note
The sum of the first k odd numbers is k², so for n = 20 (ten odd numbers) the answer is 100.
Learn the concept
New to this topic? Read the lesson, then come back.