Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Print Numbers in an Interval
In this article, we will learn how to print all numbers within a given interval using Python. We'll explore different approaches including printing all numbers, only even numbers, only odd numbers, and prime numbers in a range.
Problem Statement
Given a starting and ending range of an interval, we need to print all the numbers (or specific types of numbers) within that interval.
Method 1: Print All Numbers in an Interval
The simplest approach is to use a for loop with range() function to iterate through all numbers ?
start = 5
end = 12
print("All numbers in the interval:")
for num in range(start, end + 1):
print(num)
All numbers in the interval: 5 6 7 8 9 10 11 12
Method 2: Print Even Numbers in an Interval
To print only even numbers, we check if the number is divisible by 2 ?
start = 5
end = 15
print("Even numbers in the interval:")
for num in range(start, end + 1):
if num % 2 == 0:
print(num)
Even numbers in the interval: 6 8 10 12 14
Method 3: Print Odd Numbers in an Interval
Similarly, to print only odd numbers, we check if the number is not divisible by 2 ?
start = 5
end = 15
print("Odd numbers in the interval:")
for num in range(start, end + 1):
if num % 2 != 0:
print(num)
Odd numbers in the interval: 5 7 9 11 13 15
Method 4: Print Prime Numbers in an Interval
A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. We use nested loops to check for prime numbers ?
start = 10
end = 29
print("Prime numbers in the interval:")
for val in range(start, end + 1):
# Check if number is greater than 1
if val > 1:
# Check for factors from 2 to val-1
for n in range(2, val):
if (val % n) == 0:
break
else:
print(val)
Prime numbers in the interval: 11 13 17 19 23 29
Using Step Parameter
You can also use the step parameter in range() to print numbers with specific intervals ?
start = 2
end = 20
step = 3
print("Numbers with step 3:")
for num in range(start, end + 1, step):
print(num)
Numbers with step 3: 2 5 8 11 14 17 20
Comparison
| Method | Use Case | Time Complexity |
|---|---|---|
| All Numbers | Print every number in range | O(n) |
| Even/Odd | Filter based on divisibility | O(n) |
| Prime Numbers | Mathematical filtering | O(n²) |
| Step Parameter | Skip numbers by fixed interval | O(n/step) |
Conclusion
Python's range() function provides a flexible way to print numbers in any interval. Use simple iteration for all numbers, conditional checks for even/odd numbers, and nested loops for prime number filtering.
