Sum of All Odd Numbers Up to N

Print the sum of all odd numbers up to n.

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

What's going on

Sum only odd numbers using step 2.

Key Concepts:

Start from 1 (first odd number)
Step by 2 to get only odd numbers
Accumulate sum