Python Practice › Loop Programs › Program 4
Count even and odd numbers
Write a Python program to count the even and odd numbers in a series.
Input
(1, 2, 3, 4, 5, 6, 7, 8, 9)
Output
Number of even numbers: 4 Number of odd numbers: 5
Approach
- Keep two counters and increase one of them for each number.
Solution
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)even = odd = 0for n in numbers: if n % 2 == 0: even += 1 else: odd += 1print("Number of even numbers:", even)print("Number of odd numbers:", odd)Output
Number of even numbers: 4 Number of odd numbers: 5
Line by line
Line 2
Both counters start at 0.
Lines 4-7
Each number increases exactly one counter.
Learn the concept
New to this topic? Read the lesson, then come back.