Python Practice › Loop Programs › Program 15
Odd numbers from 1 to 100
Write a Python program to print all odd numbers from 1 to 100.
Output
[1, 3, 5, 7, 9] ... [95, 97, 99] 50 odd numbers
Approach
- Use
range(1, 100, 2).
Solution
odds = [n for n in range(1, 101) if n % 2 == 1]print(odds[:5], "...", odds[-3:])print(len(odds), "odd numbers")Output
[1, 3, 5, 7, 9] ... [95, 97, 99] 50 odd numbers
Line by line
Line 1
The comprehension keeps numbers whose remainder after dividing by 2 is 1.
Line 2
Printing only the first and last few keeps the output short.
Learn the concept
New to this topic? Read the lesson, then come back.