Sum of Odd Elements

Calculate sum of odd elements.

IntermediatePhase 4 - Level 2: Searching & Counting LogicExample 7 of 10
sum-of-odd-elements.py
1# Take array
2n = int(input("Enter array size: "))
3arr = []
4for i in range(n):
5 arr.append(int(input(f"Element {i+1}: ")))
6
7# Sum odd elements
8sum_odd = 0
9for element in arr:
10 if element % 2 != 0:
11 sum_odd += element
12
13print(f"Sum of odd elements: {sum_odd}")

Output

Enter array size: 5
Element 1: 2
Element 2: 3
Element 3: 4
Element 4: 5
Element 5: 6
Sum of odd elements: 8

What's going on

Filter odd elements and sum.

Key Concepts:

Check if element is odd
Add to sum if odd
Conditional accumulation